diff --git a/f2/utils/utils.py b/f2/utils/utils.py index 81ee8e9..9eb7b44 100644 --- a/f2/utils/utils.py +++ b/f2/utils/utils.py @@ -927,7 +927,7 @@ def aes_encrypt(self, plaintext: bytes) -> bytes: elif self.mode == "ECB": return self._aes_encrypt_ecb(plaintext) - def aes_decrypt(self, ciphertext: bytes) -> bytes: + def aes_decrypt(self, ciphertext: bytes, iv: Optional[bytes] = None) -> bytes: """ AES 解密 @@ -940,7 +940,7 @@ def aes_decrypt(self, ciphertext: bytes) -> bytes: if self.mode == "GCM": return self._aes_decrypt_gcm(ciphertext) elif self.mode == "CBC": - return self._aes_decrypt_cbc(ciphertext) + return self._aes_decrypt_cbc(ciphertext, iv) elif self.mode == "ECB": return self._aes_decrypt_ecb(ciphertext) @@ -990,17 +990,14 @@ def _aes_encrypt_cbc(self, plaintext: bytes) -> bytes: ciphertext = encryptor.update(padded_data) + encryptor.finalize() return ciphertext # 返回密文 - def _aes_decrypt_cbc(self, ciphertext: bytes) -> bytes: + def _aes_decrypt_cbc(self, ciphertext: bytes, iv: bytes) -> bytes: """CBC模式解密""" - iv = ciphertext[:16] # 获取 IV(16 字节) - ciphertext_data = ciphertext[16:] # 获取密文 - cipher = Cipher( algorithms.AES(self.key), modes.CBC(iv), backend=default_backend() ) decryptor = cipher.decryptor() - padded_plaintext = decryptor.update(ciphertext_data) + decryptor.finalize() + padded_plaintext = decryptor.update(ciphertext) + decryptor.finalize() # 去除填充 unpadder = aes_padding.PKCS7(128).unpadder() diff --git a/tests/test_aes.py b/tests/test_aes.py index 60f9c24..b454270 100644 --- a/tests/test_aes.py +++ b/tests/test_aes.py @@ -79,7 +79,7 @@ def test_aes128_gcm_encrypt_decrypt(aes128_gcm_encryption): # 测试 AES128 CBC 加密和解密 def test_aes128_cbc_encrypt_decrypt(aes128_cbc_encryption): encrypted = aes128_cbc_encryption.aes_encrypt(TEST_TEXT) - decrypted = aes128_cbc_encryption.aes_decrypt(encrypted) + decrypted = aes128_cbc_encryption.aes_decrypt(encrypted, iv=TEST_IV_CBC) assert decrypted == TEST_TEXT, "AES128 CBC 解密失败,明文不匹配" @@ -103,7 +103,7 @@ def test_aes192_gcm_encrypt_decrypt(aes192_gcm_encryption): # 测试 AES192 CBC 加密和解密 def test_aes192_cbc_encrypt_decrypt(aes192_cbc_encryption): encrypted = aes192_cbc_encryption.aes_encrypt(TEST_TEXT) - decrypted = aes192_cbc_encryption.aes_decrypt(encrypted) + decrypted = aes192_cbc_encryption.aes_decrypt(encrypted, iv=TEST_IV_CBC) assert decrypted == TEST_TEXT, "AES192 CBC 解密失败,明文不匹配" @@ -127,7 +127,7 @@ def test_aes256_gcm_encrypt_decrypt(aes256_gcm_encryption): # 测试 AES256 CBC 加密和解密 def test_aes256_cbc_encrypt_decrypt(aes256_cbc_encryption): encrypted = aes256_cbc_encryption.aes_encrypt(TEST_TEXT) - decrypted = aes256_cbc_encryption.aes_decrypt(encrypted) + decrypted = aes256_cbc_encryption.aes_decrypt(encrypted, iv=TEST_IV_CBC) assert decrypted == TEST_TEXT, "AES256 CBC 解密失败,明文不匹配"