【发布时间】:2020-10-27 08:22:02
【问题描述】:
我正在尝试在python中实现aes加密和解密。当我执行代码时,它返回错误。我已经在我的机器上安装了 anaconda。我在 jupyter notebook 中运行脚本。
!pip install pycryptodome
import base64
from Crypto import Random
from Crypto.Cipher import AES
BS = 16
pad = lambda s: s + (BS - len(s) % BS) * chr(BS - len(s) % BS)
unpad = lambda s : s[0:-ord(s[-1])]
class AESCipher:
def __init__( self, key ):
self.key = key
def encrypt( self, raw ):
raw = pad(raw)
iv = Random.new().read( AES.block_size )
cipher = AES.new( self.key, AES.MODE_CBC, iv )
return base64.b64encode( iv + cipher.encrypt( raw ) )
def decrypt( self, enc ):
enc = base64.b64decode(enc)
iv = enc[:16]
cipher = AES.new(self.key, AES.MODE_CBC, iv )
return unpad(cipher.decrypt( enc[16:] ))
cipher = AESCipher('mysecretpassword')
encrypted = cipher.encrypt('Secret')
decrypted = cipher.decrypt(encrypted)
print(encrypted)
print(decrypted)
如何解决?
【问题讨论】:
-
请修正缩进。错误是什么? (哪条线等...)
-
原始=垫(原始)。 TypeError: 对象类型
不能传递给 C 代码 -
您的代码是为 Python2 编写的,在 Python3 中
str和bytes是不同的对象。您必须用字节替换所有字符串(请参阅str.encode)。 -
我对上面的代码做了如下改动。 pwd=b"mysecretpassword" cipher = AESCipher(pwd) msg=b"Secret" encrypted = cipher.encrypt(msg) print(encrypted) print(decrypted) 它返回 TypeError: can't concat str to bytes
标签: python encryption