<
>

Python3.7 基于 pycryptodome 的AES加密解密、RSA加密解密、加签验签

2020-06-25 08:07:29 来源:易采站长站 作者:易采站长站整理


5、使用方法链调用 publickey 和 exportKey 方法生成公钥,写入磁盘上的文件。
"""
key = RSA.generate(1024)
encrypted_key = key.exportKey(passphrase=password, pkcs=8,protection="scryptAndAES128-CBC")
# encrypted_key = key.exportKey(pkcs=1)
print('encrypted_key:',encrypted_key)
with open("my_private_rsa_key.pem", "wb") as f:
f.write(encrypted_key)
with open("my_rsa_public.pem", "wb") as f:
f.write(key.publickey().exportKey())
def encrypt_and_decrypt_test(password="123456"):
# 加载私钥用于加密
recipient_key = RSA.import_key(
open("my_rsa_public.pem").read()
)
cipher_rsa = PKCS1_v1_5.new(recipient_key)
#使用base64编码保存数据方便查看,同样解密需要base64解码
en_data = base64.b64encode(cipher_rsa.encrypt(b"123456,abcdesd"))
print("加密数据信息:",type(en_data),'n',len(en_data),'n',en_data)
# 加载公钥用于解密
encoded_key = open("my_private_rsa_key.pem").read()
private_key = RSA.import_key(encoded_key,passphrase=password)
cipher_rsa = PKCS1_v1_5.new(private_key)
data = cipher_rsa.decrypt(base64.b64decode(en_data), None)
print(data)
def rsa_sign(message,password="123456"):
#读取私钥信息用于加签
private_key = RSA.importKey(open("my_private_rsa_key.pem").read(),passphrase=password)
hash_obj = SHA1.new(message)
# print(pkcs1_15.new(private_key).can_sign()) #check wheather object of pkcs1_15 can be signed
#base64编码打印可视化
signature = base64.b64encode(pkcs1_15.new(private_key).sign(hash_obj))
return signature
def rsa_signverify(message,signature):
#读取公钥信息用于验签
public_key = RSA.importKey(open("my_rsa_public.pem").read())
#message做“哈希”处理,RSA签名这么要求的
hash_obj = SHA1.new(message)
try:
#因为签名被base64编码,所以这里先解码,再验签
pkcs1_15.new(public_key).verify(hash_obj,base64.b64decode(signature))
print('The signature is valid.')
return True
except (ValueError,TypeError):
print('The signature is invalid.')
if __name__ == '__main__':
# create_rsa_key()
encrypt_and_decrypt_test()
# message = b'Luosu is a Middle-aged uncle.'
# signature = rsa_sign(message)
# print('signature:',signature)
# print(rsa_signverify(message,signature))

总结

以上所述是小编给大家介绍的Python3.7 基于 pycryptodome 的AES加密解密、RSA加密解密、加签验签,希望对大家有所帮助,如果大家有任何疑问请给我留言,小编会及时回复大家的。在此也非常感谢大家对软件开发网网站的支持!
如果你觉得本文对你有帮助,欢迎转载,烦请注明出处,谢谢!

您可能感兴趣的文章:Python3非对称加密算法RSA实例详解Python3对称加密算法AES、DES3实例详解python3.x实现base64加密和解密python3中的md5加密实例Python3 加密(hashlib和hmac)模块的实现python3.6 实现AES加密的示例(pyCryptodome)Python3内置模块之base64编解码方法详解Python使用MD5加密算法对字符串进行加密操作示例Python md5与sha1加密算法用法分析python3 常见解密加密算法实例分析【base64、MD5等】

暂时禁止评论

微信扫一扫

易采站长站微信账号