Sam*_*ami 2 encryption aes python-3.x pycryptodome
我正在编写一个简单的 AES 加密代码。我被困在一个部分,它说在加密()之后不能调用解密()。我通过互联网报废寻找解决方案,但无法这样做,可能是因为缺乏适当的文档示例。
我尝试更改这些行的顺序,但没有帮助
encrypted = encrypt(message)
decrypted = decrypt(encrypted)
Run Code Online (Sandbox Code Playgroud)
我有2个例子
示例 1
from Crypto.Cipher import AES
key = 'ACD310AE179CE245624BB238867CE189'
message = 'this is my super secret message'
cipher = AES.new(key.encode('utf-8'),AES.MODE_CBC)
def pad(s):
return s + ((16 - len(s) % 16) * '{')
def encrypt(plaintext):
global cipher
return cipher.encrypt(pad(plaintext).encode('utf-8'))
def decrypt(ciphertext):
global cipher
dec = cipher.decrypt(ciphertext).decode('utf-8')
l = dec.count('{')
return dec[:len(dec)-1]
encrypted = encrypt(message)
decrypted = decrypt(encrypted)
print("Message: ", message)
print("Encrypted: ", encrypted)
print("Decrypted: ", decrypted)
Run Code Online (Sandbox Code Playgroud)
示例 2
from Crypto.Cipher import AES
key = b'Sixteen byte key'
data = b'hello from other side'
cipher = AES.new(key, AES.MODE_EAX)
e_data = cipher.encrypt(data)
d_data = cipher.decrypt(e_data)
print("Encryption was: ", e_data)
print("Original Message was: ", d_data)
Run Code Online (Sandbox Code Playgroud)
除了官方文档之外,还请提供 pycryptodome 的有用链接,因为它不好。
该函数的文档字符串decrypt()确实提到:
A cipher object is stateful: once you have decrypted a message
you cannot decrypt (or encrypt) another message with the same
object.
Run Code Online (Sandbox Code Playgroud)
所以显然你需要在加密后创建一个新的密码对象来进行解密。官方文档有一个您可以利用的示例。像这样的东西,这是对您的示例 2 的一个小修改:
from Crypto.Cipher import AES
key = b'Sixteen byte key'
data = b'hello from other side'
e_cipher = AES.new(key, AES.MODE_EAX)
e_data = e_cipher.encrypt(data)
d_cipher = AES.new(key, AES.MODE_EAX, e_cipher.nonce)
d_data = d_cipher.decrypt(e_data)
print("Encryption was: ", e_data)
print("Original Message was: ", d_data)
Run Code Online (Sandbox Code Playgroud)
尝试一下:
$ python encdec.py
Encryption was: b'P\x06Z:QF\xc3\x9f\x8b\xc9\x83\xe6\xfd\xfa\x99\xfc\x0f\xa0\xc5\x19\xf0'
Original Message was: b'hello from other side'
Run Code Online (Sandbox Code Playgroud)