Python-RSA非对称加解密、AES对称加解密排坑
来源:https://www.cnblogs.com/zhangxingcomeon/p/14678705.html
最近做自定义TCP数据包通信,使用加解密库crypto,遇到的小问题排坑如下:
若要是使用crypto库,linux下需要按照如下包名安装
pip install pycryptodome
一、对称AES
1、Python aes加密IV is not meaningful for the ECB mode
(加不加IV)EBC不加Ⅳ, CBC模式加Ⅳ,所以EBC模式不给第三个参数,CBC模式可以加第三个参数
2、Object type class 'str' cannot be passed to C code
key ,vi,传入endtryde的data,三个数据都要变为bytes, (encode)
KEY VI 传入的data,均要为bytes,实践中注意KEY也需要encode
附:# 对称加密AES 加密
def aes_encrypt(data: str, key: bytes):
cryptor = AES.new(key.encode('utf-8'), AES.MODE_ECB)
# mode = AES.MODE_CBC
# cryptor = AES.new(key.encode('utf-8'), mode, b'0000000000000000')
ciphertext = str(base64.b64encode(cryptor.encrypt(add_to_16(data))), encoding='utf-8').replace('\n', '').encode('utf-8')
return ciphertext
# 对称加密AES 解密:
# 对称加密AES 解密
def aes_decrypt(data: bytes, key: bytes) -> str:
cryptor = AES.new(key.encode('utf-8'), AES.MODE_ECB)
plain_text = cryptor.decrypt(base64.b64decode(data))
return plain_text.decode('utf-8').rstrip('\0')
二、非对称RSA:
1、ciphertext with incorrect length rsa
若已经用encode decode64加解密过,则较长的数据已经变为了128位,无需再分段解密。
且,需看加密端要求传入的公钥N 和E (或约定的P、Q等参数),是否为16进制,若两边进制不匹配,会导致解密时无法成功,报错亦如上。会报长度问题和解密失败
附:# 非对称RSA加密
# 非对称RSA加密
def rsa_encrypt(data: bytes, public_key):
pub_key = RSA.importKey(public_key)
cipher = PKCS1_cipher.new(pub_key)
rsa_text = base64.b64encode(cipher.encrypt(data))
return rsa_text
# 非对称RSA解密
# 非对称RSA解密
def rsa_decrypt(data: bytes, private_key):
# 私钥解密
pri_key = RSA.importKey(private_key)
cipher = PKCS1_cipher.new(pri_key)
back_text = cipher.decrypt(base64.b64decode(data), 0)
print(back_text.decode('utf-8'))
return back_text.decode('utf-8')