Skip to content

Commit

Permalink
TKSS-1022: Need to re-create NativeSM4.SM4GCM instance when opmode is…
Browse files Browse the repository at this point in the history
… changed
  • Loading branch information
johnshajiang committed Dec 30, 2024
1 parent 1c4b508 commit 7c2f2ed
Show file tree
Hide file tree
Showing 3 changed files with 25 additions and 3 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -215,7 +215,7 @@ byte[] doFinal(byte[] data) {
return encrypt ? encDoFinal(data) : decDoFinal(data);
}

byte[] encDoFinal(byte[] data) {
private byte[] encDoFinal(byte[] data) {
Objects.requireNonNull(data);

byte[] lastOut = update(data);
Expand All @@ -229,7 +229,7 @@ byte[] encDoFinal(byte[] data) {
return out;
}

byte[] decDoFinal(byte[] data) {
private byte[] decDoFinal(byte[] data) {
if (data == null || data.length < SM4_GCM_TAG_LEN) {
throw new IllegalArgumentException("data must not be less than 16-bytes");
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -33,6 +33,7 @@ class SM4Crypt extends SymmetricCipher {

private static final Sweeper SWEEPER = Sweeper.instance();

private boolean opChanged = false;
private boolean decrypting = false;
private SM4Params paramSpec;
private byte[] key;
Expand Down Expand Up @@ -62,6 +63,7 @@ void init(boolean decrypting,
"Wrong key size: expected 16-byte, actual " + key.length);
}

this.opChanged = this.decrypting != decrypting;
this.decrypting = decrypting;
this.paramSpec = paramSpec;
this.key = key;
Expand All @@ -85,7 +87,7 @@ private void init() {
break;
case GCM:
gcmLastCipherBlock = new DataWindow(SM4_GCM_TAG_LEN);
if (sm4 == null) {
if (sm4 == null || opChanged) {
sm4 = new NativeSM4.SM4GCM(!decrypting, key, iv);
SWEEPER.register(this, new SweepNativeRef(sm4));
} else {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -731,6 +731,26 @@ public void testReusedIv4GCMCipher() throws Exception {
Assertions.assertArrayEquals(MESSAGE, cleartext);
}

@Test
public void testGCMWithBadTag() throws Exception {
SecretKey secretKey = new SecretKeySpec(KEY, "SM4");
GCMParameterSpec paramSpec = new GCMParameterSpec(
SM4_GCM_TAG_LEN * 8, GCM_IV);

Cipher cipher = Cipher.getInstance("SM4/GCM/NoPadding", PROVIDER);

cipher.init(Cipher.ENCRYPT_MODE, secretKey, paramSpec);
byte[] ciphertext = cipher.doFinal(MESSAGE);

// Change the tag bytes
ciphertext[ciphertext.length - 1] = 0x00;
ciphertext[ciphertext.length - 2] = 0x00;

cipher.init(Cipher.DECRYPT_MODE, secretKey, paramSpec);
Assertions.assertThrows(AEADBadTagException.class,
() -> cipher.doFinal(ciphertext));
}

@Test
public void testUpdateData() throws Exception {
testUpdateData("SM4/CBC/NoPadding", new IvParameterSpec(IV), true);
Expand Down

0 comments on commit 7c2f2ed

Please sign in to comment.