我正在尝试使用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'\xoc\x97\x8e\x1b\xa\x07\xde\x16\xa3\xf7\x10\x9f5'
当我运行时
len('x0cx97x8ex1bxa9x10anx07xdex16xa3xf7x10x9f5') in interpreter
我得到了16的回报,当我在中粘贴加密的aes代码时
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)
我觉得很奇怪。。。所以我真的不明白这是怎么回事。会通知一些帮助。
如果将x0cx97x8ex1bxa9x10anx07xdex16xa3xf7x10x9f5
直接粘贴到输入提示符中,则反斜杠将被转义。
>>> example=input("Prompt: ")
Prompt: x0cx97x8ex1bxa9x10anx07xdex16xa3xf7x10x9f5
>>> example
'\x0c\x97\x8e\x1b\xa9\x10a\n\x07\xde\x16\xa3\xf7\x10\x9f5'
>>> print(example)
x0cx97x8ex1bxa9x10anx07xdex16xa3xf7x10x9f5
通常,在传递加密值时,最好对值进行base64编码。然后在解密值之前对值进行解码。
>>> import base64
>>> enc=b'x0cx97x8ex1bxa9x10anx07xdex16xa3xf7x10x9f5'
>>> base64_enc = base64.b64encode(enc)
>>> print(base64_enc)
b'DJeOG6kQYQoH3haj9xCfNQ=='
>>>
>>> i=input("Prompt: ")
Prompt: DJeOG6kQYQoH3haj9xCfNQ==
>>>
>>> i
'DJeOG6kQYQoH3haj9xCfNQ=='
>>> denc=base64.b64decode(i)
>>> print(denc)
b'x0cx97x8ex1bxa9x10anx07xdex16xa3xf7x10x9f5'
>>> len(denc)
16