出于安全考虑,我们正在从pycryptodome移至cryptography
当使用pycryptodome编码相同的纯文本字符串时,我得到的密码文本不同于密码术,请考虑以下代码:

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)


密码学:


    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)


测试代码:

    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
        )



使用pycryptodome可以通过相同的测试代码,但是使用cryptography时可以生成更长的密文。

在这个问题上的任何帮助,不胜感激。

最佳答案

问题似乎在于AES块大小-在以前的实现(Pycryptodome)中,它在bytes中给出,而在新库(cryptography)中,它在bits中给出。

使用cryptography运行相同的代码并进行以下更改时,它将产生预期的结果:

    @staticmethod
    def _aes_pad(s):
        block_size_bytes = AES.block_size / 8
        padding_length = block_size_bytes - (len(s) % block_size_bytes)
        return s + padding_length * chr(padding_length)

关于python - Python中的AES加密-使用pycryptodome和密码术时会得到不同的结果,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/57375945/

10-09 10:10