From 035e07067aa9b9a11846e13554fdec83bb792432 Mon Sep 17 00:00:00 2001 From: John Jiang Date: Thu, 14 Nov 2024 11:11:47 +0800 Subject: [PATCH] TKSS-917: SM2 cipher would not encrypt empty message --- .../tencent/kona/crypto/provider/SM2Engine.java | 2 +- .../kona/crypto/provider/SM2CipherTest.java | 14 ++++++-------- 2 files changed, 7 insertions(+), 9 deletions(-) diff --git a/kona-crypto/src/main/java/com/tencent/kona/crypto/provider/SM2Engine.java b/kona-crypto/src/main/java/com/tencent/kona/crypto/provider/SM2Engine.java index 322a6d6a..39690435 100644 --- a/kona-crypto/src/main/java/com/tencent/kona/crypto/provider/SM2Engine.java +++ b/kona-crypto/src/main/java/com/tencent/kona/crypto/provider/SM2Engine.java @@ -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)); } diff --git a/kona-crypto/src/test/java/com/tencent/kona/crypto/provider/SM2CipherTest.java b/kona-crypto/src/test/java/com/tencent/kona/crypto/provider/SM2CipherTest.java index 5587aea5..634fc176 100644 --- a/kona-crypto/src/test/java/com/tencent/kona/crypto/provider/SM2CipherTest.java +++ b/kona-crypto/src/test/java/com/tencent/kona/crypto/provider/SM2CipherTest.java @@ -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 @@ -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 @@ -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