3

我有以下 python 脚本来使用 AES 256 加密/解密数据,您能否告诉我代码中是否有任何内容可能使加密变弱,或者是否有任何我没有考虑到使用 CBC 进行 AES 256 加密的内容模式?我已经测试了脚本,它工作正常,它正在加密和解密数据,但只是想要第二个意见。谢谢。

    from Crypto.Cipher import AES
    from Crypto import Random

    BLOCK_SIZE = 32

    INTERRUPT = u'\u0001'

    PAD = u'\u0000'

    def AddPadding(data, interrupt, pad, block_size):
        new_data = ''.join([data, interrupt])
        new_data_len = len(new_data)
        remaining_len = block_size - new_data_len
        to_pad_len = remaining_len % block_size
        pad_string = pad * to_pad_len
        return ''.join([new_data, pad_string])

    def StripPadding(data, interrupt, pad):
        return data.rstrip(pad).rstrip(interrupt)

    SECRET_KEY = Random.new().read(32)

    IV = Random.new().read(16)

    cipher_for_encryption = AES.new(SECRET_KEY, AES.MODE_CBC, IV)
    cipher_for_decryption = AES.new(SECRET_KEY, AES.MODE_CBC, IV)

    def EncryptWithAES(encrypt_cipher, plaintext_data):
        plaintext_padded = AddPadding(plaintext_data, INTERRUPT, PAD, BLOCK_SIZE)
        encrypted = encrypt_cipher.encrypt(plaintext_padded)
        return encrypted

    def DecryptWithAES(decrypt_cipher, encrypted_data):
        decoded_encrypted_data = encrypted_data
        decrypted_data = decrypt_cipher.decrypt(decoded_encrypted_data)
        return StripPadding(decrypted_data, INTERRUPT, PAD)

    our_data_to_encrypt = u'abc11100000'
    encrypted_data = EncryptWithAES(cipher_for_encryption, our_data_to_encrypt)
    print ('Encrypted string:', encrypted_data)

    decrypted_data = DecryptWithAES(cipher_for_decryption, encrypted_data)
    print ('Decrypted string:', decrypted_data)
4

1 回答 1

2

我在网上看到过代码。原则上,它没有太多问题,但没有必要发明自己的填充。此外,我不明白为什么第一个填充字符称为中断。我假设 INTERRUPT 和 PAD 作为单个字节处理(我不是 Python 专家)。

最常见的填充是 PKCS#5 填充。它由 N 个字节组成,其值为填充字节数。这里使用的填充看起来更像“ISO”填充,它由一个设置为 1 的位组成,以将其与数据和其他填充位区分开来,其余的都是零。那将是代码中的代码点 \u0080。

所以加密(可以提供数据的机密性)似乎被正确使用了。如果您还需要完整性保护和/或身份验证,例如通过使用 MAC 或 HMAC,这取决于用例。当然,没有提供任何法律保证或任何东西。

于 2011-12-01T22:01:26.743 回答