Skip to content

Commit

Permalink
TKSS-917: SM2 cipher would not encrypt empty message
Browse files Browse the repository at this point in the history
  • Loading branch information
johnshajiang committed Nov 14, 2024
1 parent 8a846bc commit 035e070
Show file tree
Hide file tree
Showing 2 changed files with 7 additions and 9 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -258,7 +258,7 @@ private byte[] kdf(byte[] input, int keyLen) {
}

private static boolean checkInputBound(byte[] input, int offset, int len) {
return input != null
return input != null && input.length > 0
&& offset >= 0 && len >= 0
&& (input.length >= (offset + len));
}
Expand Down
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
/*
* Copyright (C) 2022, 2023, THL A29 Limited, a Tencent company. All rights reserved.
* Copyright (C) 2022, 2024, THL A29 Limited, a Tencent company. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
Expand Down Expand Up @@ -308,13 +308,12 @@ public void testEmptyInput() throws Exception {
Cipher cipher = Cipher.getInstance("SM2", PROVIDER);

cipher.init(Cipher.ENCRYPT_MODE, pubKey);
byte[] ciphertext = cipher.doFinal(EMPTY);
Assertions.assertThrows(BadPaddingException.class,
() -> cipher.doFinal(EMPTY));

cipher.init(Cipher.DECRYPT_MODE, priKey);
Assertions.assertThrows(BadPaddingException.class,
() -> cipher.doFinal(EMPTY));
byte[] cleartext = cipher.doFinal(ciphertext);
Assertions.assertArrayEquals(EMPTY, cleartext);
}

@Test
Expand All @@ -329,16 +328,15 @@ public void testEmptyInputWithByteBuffer() throws Exception {

cipher.init(Cipher.ENCRYPT_MODE, pubKey);
ByteBuffer ciphertextBuf = ByteBuffer.allocate(150);
cipher.doFinal(ByteBuffer.allocate(0), ciphertextBuf);

Assertions.assertThrows(BadPaddingException.class,
() -> cipher.doFinal(ByteBuffer.allocate(0), ciphertextBuf));
ciphertextBuf.flip();

cipher.init(Cipher.DECRYPT_MODE, priKey);
ByteBuffer cleartextBuf = ByteBuffer.allocate(150);
Assertions.assertThrows(BadPaddingException.class,
() -> cipher.doFinal(ByteBuffer.allocate(0), cleartextBuf));
cipher.doFinal(ciphertextBuf, cleartextBuf);

Assertions.assertEquals(0, cleartextBuf.position());
}

@Test
Expand Down

0 comments on commit 035e070

Please sign in to comment.