我正在尝试在python中实现AES加密和解密。当我执行代码时,它返回错误。我已经在计算机上安装了anaconda。我正在jupyter笔记本中运行脚本。
!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)
如何解决这个问题?
答案 0 :(得分:0)
只需将unpad更新为unpad = lambda s : s[0:-ord(s[-1:])]
如果您尝试打印 s [-1] 的值,则ord()期望长度为一的字符串的主要问题是它打印的 10 不是一个字符,而是 s [-1:] 的打印值为 b'\ n',即一个字符
还将密钥编码为字节bytes(key, 'utf-8')
和填充
pad = lambda s: bytes(s + (BS - len(s) % BS) * chr(BS - len(s) % BS), 'utf-8')
确保所有输入均为字节
from hashlib import sha256
import base64
from Crypto import Random
from Crypto.Cipher import AES
BS = 16
pad = lambda s: bytes(s + (BS - len(s) % BS) * chr(BS - len(s) % BS), 'utf-8')
unpad = lambda s : s[0:-ord(s[-1:])]
class AESCipher:
def __init__( self, key ):
self.key = bytes(key, 'utf-8')
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:] )).decode('utf8')
cipher = AESCipher('mysecretpassword')
encrypted = cipher.encrypt('Secret')
decrypted = cipher.decrypt(encrypted)
print(encrypted)
print(decrypted)
答案 1 :(得分:0)
///第一个pip安装pycryptodome-(pycrypto已过时并出现问题) // pip安装pkcs7
from Crypto import Random
from Crypto.Cipher import AES
import base64
from pkcs7 import PKCS7Encoder
from app_settings.views import retrieve_settings # my custom settings
app_secrets = retrieve_settings(file_name='secrets');
def encrypt_data(text_data):
#limit to 16 bytes because my encryption key was too long
#yours could just be 'abcdefghwhatever'
encryption_key = app_secrets['ENCRYPTION_KEY'][:16];
#convert to bytes. same as bytes(encryption_key, 'utf-8')
encryption_key = str.encode(encryption_key);
#pad
encoder = PKCS7Encoder();
raw = encoder.encode(text_data) # Padding
iv = Random.new().read(AES.block_size ) #AES.block_size defaults to 16
# no need to set segment_size=BLAH
cipher = AES.new( encryption_key, AES.MODE_CBC, iv )
encrypted_text = base64.b64encode( iv + cipher.encrypt( str.encode(raw) ) )
return encrypted_text;