python 在 Windows下使用密码库时要安装的是pycryptodome模块
pip install pycryptodome
python 在 Linux下使用密码库时要安装的是pycrypto模块
pip install pycrypto
#-*- coding:utf-8 -*-
from Crypto import Random
output_bytes = Random.get_random_bytes(nLength)
#-*- coding:utf-8 -*-
from Crypto.Cipher import AES
cipher = AES.new(bytes(key), AES.MODE_CBC, bytes(IV))
output_bytes = cipher.encrypt(bytes(input_bytes)) # 加密
output_bytes = cipher.decrypt(bytes(input_bytes)) # 解密
#-*- coding:utf-8 -*-
from Crypto.PublicKey import RSA
from Crypto import Random
import Crypto.Cipher.PKCS1_v1_5
import Crypto.Signature.PKCS1_v1_5
from Crypto import Hash
'''rsa key生成'''
rsakey = RSA.generate(2048, Random.new().read) # 使用 Random.new().read 伪随机数生成器
pri_key = rsakey.exportKey("PEM") # 生成私钥
pub_key = rsakey.publickey().exportKey("PEM") # 生成公钥
with open("Kkb_pri.pem", "wb+") as f_pri_key:
f_pri_key.write(pri_key)
with open("Kkb_pub.pem", "wb+") as f_pub_key:
f_pub_key.write(pub_key)
'''
pri_key = rsakey.exportKey("DER") # 生成DER格式的私钥
with open("Kkb_pri", "wb+") as f_pri_key:
f_pri_key.write(pri_key)
'''
message = b"012456789abcdef"
'''rsa加解密'''
with open("Kkb_pub.pem", "rb") as f_pub_key:
pub_key = f_pub_key.read()
cipher_public = Crypto.Cipher.PKCS1_v1_5.new(RSA.importKey(pub_key))
cipher_text = cipher_public.encrypt(message) # 使用公钥进行加密
with open("Kkb_pri.pem", "rb") as f_pri_key:
pri_key = f_pri_key.read()
# 如果私钥有密码 则使用相应密码RSA.importKey(pri_key, password)
cipher_private = Crypto.Cipher.PKCS1_v1_5.new(RSA.importKey(pri_key))
text = cipher_private.decrypt(cipher_text, Random.new().read) # 使用私钥进行解密(第二个参数用于返回错误信息,可直接为0或'')
print(text == message) # 对比验证
'''rsa数字签名'''
with open("Kkb_pri.pem", "rb") as f_pri_key:
pri_key = f_pri_key.read()
pri_key_rsa = RSA.importKey(pri_key)
signer = Crypto.Signature.PKCS1_v1_5.new(pri_key_rsa)
msg_hash = Hash.SHA256.new()
msg_hash.update(message)
sign = signer.sign(msg_hash) # 使用私钥进行'sha256'签名
with open("Kkb_pub.pem", "rb") as f_pub_key:
pub_key = f_pub_key.read()
pub_key_rsa = RSA.importKey(pub_key)
verifer = Crypto.Signature.PKCS1_v1_5.new(pub_key_rsa)
msg_hash = Hash.SHA256.new()
msg_hash.update(message)
verify = verifer.verify(msg_hash, sign) # 使用公钥验证签名
print(verify)
本文直接处理bytes数据,常见的是将数据进行base64编解码,关于base64编解码参考
base64介绍
官方文档
https://github.com/pycrypto/pycrypto
https://www.dlitz.net/software/pycrypto/api/current/
参考链接
https://blog.csdn.net/whatday/article/details/97617461/
https://blog.csdn.net/weixin_31473011/article/details/112524152
https://blog.csdn.net/alongsxmx/article/details/91039437