AES 256加密与使用CBC模式的PyCrypto-有什么弱点吗?

2024-10-02 12:30:01 发布

您现在位置:Python中文网/ 问答频道 /正文

我有下面的python脚本来使用AES 256加密/解密数据,您能告诉我代码中是否有任何东西可能会使加密变弱,或者在使用CBC模式的aes256加密中是否有任何东西我没有考虑到?我已经测试过这个脚本,它工作得很好,它正在加密和解密数据,但只是想要一个第二意见。谢谢。

    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)

Tags: tonewfordatastringlenreturndef
1条回答
网友
1楼 · 发布于 2024-10-02 12:30:01

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

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

因此加密(可以提供数据的机密性)似乎被正确地使用。这取决于您是否还需要完整性保护和/或身份验证,例如使用MAC或HMAC。当然,没有法律保证或任何规定。

相关问题 更多 >

    热门问题