【问题标题】:TypeError: decrypt() cannot be called after encrypt()TypeError:encrypt() 后不能调用decrypt()
【发布时间】:2019-06-02 14:00:36
【问题描述】:

我正在编写一个简单的 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)

【问题讨论】:

标签: python-3.x encryption aes pycryptodome


【解决方案1】:

docstring for the decrypt() function 确实提到:

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

显然,您需要在加密后创建一个新的密码对象来进行解密。官方文档有an example which you can leverage。像这样,这是对您的示例 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'

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2018-12-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多