更改 AES 加密的默认长度倍数

Change Default Multiple in Length for AES Encryption

我创建了一个函数,它使用 Crypto.Cipher:

    import os
    from Crypto.Cipher import AES

    def encrypt_pass(user_entered_plaintext):
        encrypt_setup = AES.new(os.urandom(32), AES.MODE_CBC, os.urandom(16))
        plaintext = user_entered_plaintext
        ciphertext = encrypt_setup.encrypt(plaintext)

        print(ciphertext)
        return ciphertext

如果我尝试 运行 这个,比如:

encrypt_pass('Test')

我收到此错误:

ValueError: Input strings must be a multiple of 16 in length

如果我尝试更改:

encrypt_setup = AES.new(os.urandom(32), AES.MODE_CBC, os.urandom(16))

encrypt_setup = AES.new(os.urandom(32), AES.MODE_CBC, os.urandom(8))

我得到:

ValueError: IV must be 16 bytes long

如何将此输入字符串的最小值强制为 8?

只需指定 PKCS#7 填充。您必须在加密之前添加它并在解密之后将其删除,因为编写 pycrypto 的笨蛋没有将填充作为选项添加。 (而且我认为 PHP mcrypt 不好!)请参阅 CodeTalk 的 link。

AES 加密是基于块的,块大小为 16 字节,因此如果输入数据不是块大小的倍数,则必须添加填充。

在第二次尝试中,您将 iv 更改为 8 字节,但它必须是 16 字节的块大小。

但是您没有保存密钥或 iv,因此您以后将无法解密数据。你需要为他们使用变量。