We're moving away from pycryptodome to cryptography due to security considerations. When encoding the same plain-text string with pycryptodome I get a different cypher text than cryptography, consider the following code:
Pycryptodome:
def aes_encrypt(self, plain_text): try: plain_text_with_padding = self._aes_pad(plain_text).encode("utf-8") cipher = AES.new(self.aes_secret_key, AES.MODE_CBC, self.aes_iv) msg = cipher.encrypt(plain_text_with_padding) return msg.encode("hex") except Exception as e: raise AesError(e.message) Cryptography:
def aes_encrypt(self, plain_text): try: plain_text_with_padding = self._aes_pad(plain_text) encryptor = Cipher( algorithm=algorithms.AES(self.aes_secret_key), mode=modes.CBC(self.aes_iv), backend=default_backend(), ).encryptor() msg = encryptor.update(plain_text_with_padding) + encryptor.finalize() return msg.encode("hex") except Exception as e: raise AesError(e.message) @staticmethod def _aes_pad(s): padding_length = AES.block_size - (len(s) % AES.block_size) return s + padding_length * chr(padding_length) The test code:
def setUp(self): secret_manager = Mock() secret_manager.get_secret.return_value = { "hmac_secret_key": "secret", "aes_secret_key": "fbc1f4bf4c826fc41d27905bc3eb8cbb", "aes_iv": "J3wmcjV0Vzd9Jw==" } self.crypto_utils = CryptoUtils(secret_manager) def test_aes_encrypt(self): asset_id = "123456" encrypted_asset_id = self.crypto_utils.aes_encrypt(asset_id) self.assertEqual( "926fbb0584c6e357157709e723b0e0d2", encrypted_asset_id ) The same test code pass using pycryptodome but generate much longer cipher text when using cryptography.
Any help on this matter is appreciated.
msg = encryptor.update(plain_text_with_padding) + encryptor.finalize()should bemsg = encryptor.finalize().