3

我正在编写一个简单的 AES 加密代码,但我被困在它说的部分:

TypeError:decrypt()之后无法调用encrypt()

我尝试更改这些行的顺序,但没有帮助:

encrypted = encrypt(message)
decrypted = decrypt(encrypted)

我有两个例子:

示例 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)

示例 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)
4

1 回答 1

6

函数的文档字符串decrypt()确实提到:

A cipher object is stateful: once you have decrypted a message
    you cannot decrypt (or encrypt) another message with the same
    object.

所以显然你需要在加密后创建一个新的密码对象来进行解密。官方文档有一个你可以利用的例子。像这样的东西,这是对您的示例 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)

尝试一下:

$ 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'
于 2019-01-07T22:39:17.087 回答