【问题标题】:ValueError: AES key must be either 16, 24, or 32 bytes long PyCrypto 2.7a1ValueError:AES 密钥必须是 16、24 或 32 字节长 PyCrypto 2.7a1
【发布时间】:2016-08-20 10:51:39
【问题描述】:

我正在为我的学校项目制作程序,但上面有一个问题。 这是我的代码:

def aes():
    #aes
    os.system('cls')
    print('1. Encrypt')
    print('2. Decrypt')

    c = input('Your choice:')

    if int(c) == 1:
        #cipher
        os.system('cls')
        print("Let's encrypt, alright")
        print('Input a text to be encrypted')
        text = input()

        f = open('plaintext.txt', 'w')
        f.write(text)
        f.close()

        BLOCK_SIZE = 32
        PADDING = '{'
        pad = lambda s: s + (BLOCK_SIZE - len(s) % BLOCK_SIZE) * PADDING
        EncodeAES = lambda c, s: base64.b64encode(c.encrypt(pad(s)))
        secret = os.urandom(BLOCK_SIZE)

        f = open('aeskey.txt', 'w')
        f.write(str(secret))
        f.close()

        f = open('plaintext.txt', 'r')
        privateInfo = f.read()
        f.close()

        cipher = AES.new(secret)

        encoded = EncodeAES(cipher, privateInfo)

        f = open('plaintext.txt', 'w')
        f.write(str(encoded))
        f.close()
        print(str(encoded))

    if int(c) == 2:
        os.system('cls')
        print("Let's decrypt, alright")

        f = open('plaintext.txt','r')
        encryptedString = f.read()
        f.close()

        PADDING = '{'
        DecodeAES = lambda c, e: c.decrypt(base64.b64decode(e)).rstrip(PADDING)
        encryption = encryptedString

        f = open('aeskey.txt', 'r')
        key = f.read()
        f.close()

        cipher = AES.new(key)
        decoded = DecodeAES(cipher, encryption)

        f = open('plaintext.txt', 'w')
        f.write(decoded)
        f.close()

        print(decoded)

完整的错误文本:

Traceback (most recent call last): File "C:/Users/vital/Desktop/Prog/Python/Enc_dec/Enc_dec.py", line 341, in aes() 
File "C:/Users/vital/Desktop/Prog/Python/Enc_dec/Enc_dec.py", line 180, in aes cipher = AES.new(key) 
File "C:\Users\vital\AppData\Local\Programs\Python\Python35-32\lib\site-packages\Crypto\Cipher\AES.py", line 179, in new return AESCipher(key, *args, **kwargs) 
File "C:\Users\vital\AppData\Local\Programs\Python\Python35-32\lib\site-packages\Crypto\Cipher\AES.py", line 114, in init blockalgo.BlockAlgo.init(self, _AES, key, *args, **kwargs) 
File "C:\Users\vital\AppData\Local\Programs\Python\Python35-32\lib\site-packages\Crypto\Cipher\blockalgo.py", line 401, in init self._cipher = factory.new(key, *args, **kwargs)
ValueError: AES key must be either 16, 24, or 32 bytes long

Process finished with exit code 1

我做错了什么?

【问题讨论】:

  • 它是 3.5,它是 pycrypto 2.7a1 的版本

标签: python python-3.x cryptography pycrypto


【解决方案1】:

错误很明显。密钥必须正好是那个大小。 os.urandom 将返回正确的密钥。但是,此键是 bytes(二进制字符串值)。此外,通过使用str(secret)repr(secret) 的值被写入文件而不是secret

更令人困惑的是AES.new 允许您将密钥作为Unicode 传递!但是,假设密钥是 ASCII 字节 1234123412341234。现在,

f.write(str(secret))

会将b'1234123412341234' 写入文本文件!它现在包含这 16 个字节 + b 和两个 ' 引号字符,而不是 16 个字节;共 19 个字节。

或者,如果您从os.urandom 中获取随机二进制字符串,

>>> os.urandom(16)
b'\xd7\x82K^\x7fe[\x9e\x96\xcb9\xbf\xa0\xd9s\xcb'

现在,它不再写入 16 个字节 D782、.. 等等,而是将该字符串写入文件中。并且发生错误是因为解密尝试使用

"b'\\xd7\\x82K^\\x7fe[\\x9e\\x96\\xcb9\\xbf\\xa0\\xd9s\\xcb'"

作为解密密钥,当编码为 UTF-8 时会产生

b"b'\\xd7\\x82K^\\x7fe[\\x9e\\x96\\xcb9\\xbf\\xa0\\xd9s\\xcb'"

这是一个 49 字节长的 bytes 值。


您有 2 个不错的选择。您要么继续将密钥写入文本文件,但将其转换为十六进制,要么将密钥写入二进制文件;那么该文件应该正是以字节为单位的密钥长度。我在这里选择后者:

因此要存储密钥,请使用

    with open('aeskey.bin', 'wb') as keyfile:
        keyfile.write(secret)

    with open('aeskey.bin', 'rb') as keyfile:
        key = keyfile.read()

同样适用于密文(即加密的二进制文件),您必须在二进制文件中写入和读取:

    with open('ciphertext.bin', 'wb') as f:
        f.write(encoded)

    with open('ciphertext.bin', 'rb') as f:
        encryptedString = f.read()

如果您想对其进行 base64 编码,请注意 base64.b64encode/decodebytes-in/bytes-out。

顺便说一句,plaintext 是原始的未加密文本;加密的文本称为ciphertext。 AES是一种密码,可以将明文加密为密文,并使用密钥将密文解密为明文。

尽管它们被称为“-text”,但它们本身都不是 Python 所理解的文本数据,而是二进制数据,应表示为 bytes

【讨论】:

  • 对不起,但现在我有新错误:ValueError: Input strings must be a multiple of 16 in length
  • 行:decoded = DecodeAES(cipher, encryption) DecodeAES = lambda c, e: c.decrypt(base64.b64decode(e)).rstrip(PADDING)
  • @ВиталикЛукьянов 将同样的内容应用于您的密文!以二进制形式打开密文文件,并将二进制写入其中。它不是“纯文本”,可能不应该写入名为 plaintext.txt 的文件。
  • "TypeError: a bytes-like object is required, not 'str'" in lines: decoded = DecodeAES(cipher, encryption) DecodeAES = lambda c, e: c.decrypt(base64.b64decode( e)).rstrip(PADDING)
  • b'{' 怎么样。请确保您thoroughly understand the bytes/str distinction。它是这里一切的基础。
猜你喜欢
  • 1970-01-01
  • 2015-11-02
  • 1970-01-01
  • 2023-03-25
  • 2019-09-30
  • 1970-01-01
  • 2020-04-28
  • 1970-01-01
相关资源
最近更新 更多