输入字符串的长度必须是16的整数倍python pycrypto

时间:2018-07-27 00:22:53

标签: python python-3.x aes pycrypto

我正在尝试使用python进行加密,并提出了一个问题。这是我为学习和测试所做的一些代码。

#!/usr/bin/python3
import getpass
from Crypto.Cipher import AES
import hashlib
import random
import sys
import os

the_input = getpass.getpass("Enter password: ")
theHash = hashlib.sha256(the_input.encode("utf-8")).hexdigest()

key = theHash[0:16]
#IV = ''.join([chr(random.randint(0, 0xff)) for i in range(16)])
IV = os.urandom(16)
print("THEHASH: ", key, "Leangth: ", len(key))
print( "IVlen: ", len(IV), "|SYS,GETSIZEOF: ", sys.getsizeof(IV))
print("This is the IV: ", IV)
def Encrypt_str():
    aes1 = AES.new(key, AES.MODE_CBC, IV)
    data = 'whatevertest'.zfill(16)

    encr = aes1.encrypt(data)
    print("The ENCRYPTION: ",encr)
    aes2 = AES.new(key, AES.MODE_CBC, IV)
    decr = aes2.decrypt(encr)
    print("Decrypted: ", decr)

def Decrypt_str():
    aes2 = AES.new(key, AES.MODE_CBC, IV)
    inpa1 = input("Enter cip:")
    decr = aes2.decrypt(inpa1)
    print(decr)

Encrypt_str()
Decrypt_str()

在线

print("The ENCRYPTION: ",encr)

它以.zfill(16)个字节打印加密的代码

该代码为b'\ x0c \ x97 \ x8e \ x1b \ xa9 \ x10a \ n \ x07 \ xde \ x16 \ xa3 \ xf7 \ x10 \ x9f5'

我在跑步的时候

len('\x0c\x97\x8e\x1b\xa9\x10a\n\x07\xde\x16\xa3\xf7\x10\x9f5') in interpreter

当我将加密的aes代码粘贴到

中时,我得到16
inpa1 = input("Enter cip:")

我要

File "newtest.py", line 35, in <module>
    Decrypt_str()
  File "newtest.py", line 31, in Decrypt_str
    decr = aes2.decrypt(inpa1)
  File "/usr/lib/python3/dist-packages/Crypto/Cipher/blockalgo.py", line 295, i$
    return self._cipher.decrypt(ciphertext)
ValueError: Input strings must be a multiple of 16 in length

但是我仍然可以使用相同的功能解密相同的16个字节

decr = aes2.decrypt(encr)

我觉得这很奇怪...所以我无法真正了解其工作原理。会有帮助。

1 个答案:

答案 0 :(得分:0)

如果将\x0c\x97\x8e\x1b\xa9\x10a\n\x07\xde\x16\xa3\xf7\x10\x9f5直接粘贴到输入提示中,则反斜杠将被转义。

>>> example=input("Prompt: ")
Prompt: \x0c\x97\x8e\x1b\xa9\x10a\n\x07\xde\x16\xa3\xf7\x10\x9f5
>>> example
'\\x0c\\x97\\x8e\\x1b\\xa9\\x10a\\n\\x07\\xde\\x16\\xa3\\xf7\\x10\\x9f5'
>>> print(example)
\x0c\x97\x8e\x1b\xa9\x10a\n\x07\xde\x16\xa3\xf7\x10\x9f5

通常,在传递加密值时,最好对base64进行编码。然后对这些值进行解码,然后再解密该值。

>>> import base64
>>> enc=b'\x0c\x97\x8e\x1b\xa9\x10a\n\x07\xde\x16\xa3\xf7\x10\x9f5'
>>> base64_enc = base64.b64encode(enc)
>>> print(base64_enc)
b'DJeOG6kQYQoH3haj9xCfNQ=='
>>>
>>> i=input("Prompt: ")
Prompt: DJeOG6kQYQoH3haj9xCfNQ==
>>>
>>> i
'DJeOG6kQYQoH3haj9xCfNQ=='
>>> denc=base64.b64decode(i)
>>> print(denc)
b'\x0c\x97\x8e\x1b\xa9\x10a\n\x07\xde\x16\xa3\xf7\x10\x9f5'
>>> len(denc)
16