python中用于RSA加解密的库有好久个,本文主要讲解rsa、M2Crypto、Crypto这三个库对于RSA加密、解密、签名、验签的知识点。
加密是为了保证传输内容隐私,签名是为了保证消息真实性。
服务器存私钥,客户端存公钥。(服务器和客户端关系可以考虑为 1:N)
客户端往服务器传输内容,更多考虑是隐私性,所以公钥签名、私钥解密。
服务器往客户端传输内容,更多考虑真实性,所以私钥签名,公钥验签。
消息的摘要生的算法常用的是MD5或者SHA1,消息内容不一样,生成的摘要信息一定不一样。
真实性的考虑一方面是内容由私钥拥有者发出,另一方面内容在传输过程中没有改变过,所以签名的对象是传输信息生成的消息摘要(摘要内容短,签名也会快些)。
每次加密的长度需要小于密钥长度-特殊位(128位公钥,最长可加密128-11=117位明文)。
每次解密的长度需要小于密钥的长度(128位私钥解密,解密密文长度需要小于等于128位)。
如果加解密内容过长,就需要分段加密、解密。
PEM格式的密钥为base64位文本格式。
环境:MAC
python版本:2.7.15(因为公司用的版本都是这个,建议用python3的)
IED:PyCharm
密钥:PEM文件
# -*- coding: UTF-8 -*- # ! /usr/bin/env python import base64 import rsa from rsa import common # 使用 rsa库进行RSA签名和加解密 class RsaUtil(object): PUBLIC_KEY_PATH = ‘/Users/anonyper/Desktop/key/company_rsa_public_key.pem‘ # 公钥 PRIVATE_KEY_PATH = ‘/Users/anonyper/Desktop/key/company_rsa_private_key.pem‘ # 私钥 # 初始化key def __init__(self, company_pub_file=PUBLIC_KEY_PATH, company_pri_file=PRIVATE_KEY_PATH): if company_pub_file: self.company_public_key = rsa.PublicKey.load_pkcs1_openssl_pem(open(company_pub_file).read()) if company_pri_file: self.company_private_key = rsa.PrivateKey.load_pkcs1(open(company_pri_file).read()) def get_max_length(self, rsa_key, encrypt=True): """加密内容过长时 需要分段加密 换算每一段的长度. :param rsa_key: 钥匙. :param encrypt: 是否是加密. """ blocksize = common.byte_size(rsa_key.n) reserve_size = 11 # 预留位为11 if not encrypt: # 解密时不需要考虑预留位 reserve_size = 0 maxlength = blocksize - reserve_size return maxlength # 加密 支付方公钥 def encrypt_by_public_key(self, message): """使用公钥加密. :param message: 需要加密的内容. 加密之后需要对接过进行base64转码 """ encrypt_result = b‘‘ max_length = self.get_max_length(self.company_public_key) while message: input = message[:max_length] message = message[max_length:] out = rsa.encrypt(input, self.company_public_key) encrypt_result += out encrypt_result = base64.b64encode(encrypt_result) return encrypt_result def decrypt_by_private_key(self, message): """使用私钥解密. :param message: 需要加密的内容. 解密之后的内容直接是字符串,不需要在进行转义 """ decrypt_result = b"" max_length = self.get_max_length(self.company_private_key, False) decrypt_message = base64.b64decode(message) while decrypt_message: input = decrypt_message[:max_length] decrypt_message = decrypt_message[max_length:] out = rsa.decrypt(input, self.company_private_key) decrypt_result += out return decrypt_result # 签名 商户私钥 base64转码 def sign_by_private_key(self, data): """私钥签名. :param data: 需要签名的内容. 使用SHA-1 方法进行签名(也可以使用MD5) 签名之后,需要转义后输出 """ signature = rsa.sign(str(data), priv_key=self.company_private_key, hash=‘SHA-1‘) return base64.b64encode(signature) def verify_by_public_key(self, message, signature): """公钥验签. :param message: 验签的内容. :param signature: 对验签内容签名的值(签名之后,会进行b64encode转码,所以验签前也需转码). """ signature = base64.b64decode(signature) return rsa.verify(message, signature, self.company_public_key) message = ‘hell world‘ print("明文内容:>>> ") print(message) rsaUtil = RsaUtil() encrypy_result = rsaUtil.encrypt_by_public_key(message) print("加密结果:>>> ") print(encrypy_result) decrypt_result = rsaUtil.decrypt_by_private_key(encrypy_result) print("解密结果:>>> ") print(decrypt_result) sign = rsaUtil.sign_by_private_key(message) print("签名结果:>>> ") print(sign) print("验签结果:>>> ") print(rsaUtil.verify_by_public_key(message, sign)) #执行结果 明文内容:>>> hell world 加密结果:>>> sWx9r30CCLXip0iemCb2r1gsZIedgLp1Vmk9uCDaQttcQNftwQyI98shN2Hpn7snE27ziJnH6qYmaf68TWBerhJVGEzr16wLYInVft0Bj0+kcCmLL7tMJRZWydqHi/YzgIfsFEvqLOUFv6E9bCAXhJkikacBAG4FWTMBrXUQHjE= 解密结果:>>> hell world 签名结果:>>> GS3MPpb4zMLIL7mqcxZEevOoH1Fse9fjHefWIUpDaMplhoPUNK85TreYmOwvF8QJNxgLcJoKKfRm51gemsQd1/e1FBPo/4VS3kvneJyLUtQAPdOOl+R4h//0gFec+ELI+KS8A74Dkm2bFKztZ4BxIcWD63pHRiGAnS8+cQeq2QM= 验签结果:>>> True
# -*- coding: UTF-8 -*- # ! /usr/bin/env python import base64 from Crypto.Cipher import PKCS1_v1_5 as PKCS1_v1_5_cipper from Crypto.Signature import PKCS1_v1_5 from Crypto.PublicKey import RSA from Crypto.Hash import SHA import Crypto # 使用 rsa库进行RSA签名和加解密 class RsaUtil(object): PUBLIC_KEY_PATH = ‘/Users/anonyper/Desktop/key/company_rsa_public_key.pem‘ # 公钥 PRIVATE_KEY_PATH = ‘/Users/anonyper/Desktop/key/company_rsa_private_key.pem‘ # 私钥 # 初始化key def __init__(self, company_pub_file=PUBLIC_KEY_PATH, company_pri_file=PRIVATE_KEY_PATH): if company_pub_file: self.company_public_key = RSA.importKey(open(company_pub_file).read()) if company_pri_file: self.company_private_key = RSA.importKey(open(company_pri_file).read()) def get_max_length(self, rsa_key, encrypt=True): """加密内容过长时 需要分段加密 换算每一段的长度. :param rsa_key: 钥匙. :param encrypt: 是否是加密. """ blocksize = Crypto.Util.number.size(rsa_key.n) / 8 reserve_size = 11 # 预留位为11 if not encrypt: # 解密时不需要考虑预留位 reserve_size = 0 maxlength = blocksize - reserve_size return maxlength # 加密 支付方公钥 def encrypt_by_public_key(self, encrypt_message): """使用公钥加密. :param encrypt_message: 需要加密的内容. 加密之后需要对接过进行base64转码 """ encrypt_result = b‘‘ max_length = self.get_max_length(self.company_public_key) cipher = PKCS1_v1_5_cipper.new(self.company_public_key) while encrypt_message: input_data = encrypt_message[:max_length] encrypt_message = encrypt_message[max_length:] out_data = cipher.encrypt(input_data) encrypt_result += out_data encrypt_result = base64.b64encode(encrypt_result) return encrypt_result # 加密 支付方私钥 def encrypt_by_private_key(self, encrypt_message): """使用私钥加密. :param encrypt_message: 需要加密的内容. 加密之后需要对接过进行base64转码 """ encrypt_result = b‘‘ max_length = self.get_max_length(self.company_private_key) cipher = PKCS1_v1_5_cipper.new(self.company_public_key) while encrypt_message: input_data = encrypt_message[:max_length] encrypt_message = encrypt_message[max_length:] out_data = cipher.encrypt(input_data) encrypt_result += out_data encrypt_result = base64.b64encode(encrypt_result) return encrypt_result def decrypt_by_public_key(self, decrypt_message): """使用公钥解密. :param decrypt_message: 需要解密的内容. 解密之后的内容直接是字符串,不需要在进行转义 """ decrypt_result = b"" max_length = self.get_max_length(self.company_public_key, False) decrypt_message = base64.b64decode(decrypt_message) cipher = PKCS1_v1_5_cipper.new(self.company_public_key) while decrypt_message: input_data = decrypt_message[:max_length] decrypt_message = decrypt_message[max_length:] out_data = cipher.decrypt(input_data, ‘‘) decrypt_result += out_data return decrypt_result def decrypt_by_private_key(self, decrypt_message): """使用私钥解密. :param decrypt_message: 需要解密的内容. 解密之后的内容直接是字符串,不需要在进行转义 """ decrypt_result = b"" max_length = self.get_max_length(self.company_private_key, False) decrypt_message = base64.b64decode(decrypt_message) cipher = PKCS1_v1_5_cipper.new(self.company_private_key) while decrypt_message: input_data = decrypt_message[:max_length] decrypt_message = decrypt_message[max_length:] out_data = cipher.decrypt(input_data, ‘‘) decrypt_result += out_data return decrypt_result # 签名 商户私钥 base64转码 def sign_by_private_key(self, message): """私钥签名. :param message: 需要签名的内容. 签名之后,需要转义后输出 """ cipher = PKCS1_v1_5.new(self.company_private_key) # 用公钥签名,会报错 raise TypeError("No private key") 如下 # if not self.has_private(): # raise TypeError("No private key") hs = SHA.new(message) signature = cipher.sign(hs) return base64.b64encode(signature) def verify_by_public_key(self, message, signature): """公钥验签. :param message: 验签的内容. :param signature: 对验签内容签名的值(签名之后,会进行b64encode转码,所以验签前也需转码). """ signature = base64.b64decode(signature) cipher = PKCS1_v1_5.new(self.company_public_key) hs = SHA.new(message) # digest = hashlib.sha1(message).digest() # 内容摘要的生成方法有很多种,只要签名和解签用的是一样的就可以 return cipher.verify(hs, signature) message = ‘hell worldhell worldhell worldhell worldhell worldhell worldhell worldhell worldhell worldhell worldhell worldhell worldhell worldhell worldhell worldhell worldhell worldhell worldhell world‘ print("明文内容:>>> ") print(message) rsaUtil = RsaUtil() encrypy_result = rsaUtil.encrypt_by_public_key(message) print("加密结果:>>> ") print(encrypy_result) decrypt_result = rsaUtil.decrypt_by_private_key(encrypy_result) print("解密结果:>>> ") print(decrypt_result) sign = rsaUtil.sign_by_private_key(message) print("签名结果:>>> ") print(sign) print("验签结果:>>> ") print(rsaUtil.verify_by_public_key(message, sign)) #执行结果: 明文内容:>>> hell worldhell worldhell worldhell worldhell worldhell worldhell worldhell worldhell worldhell worldhell worldhell worldhell worldhell worldhell worldhell worldhell worldhell worldhell world 加密结果:>>> PC8/knkmszKby2pHtlKJa/Uv7EADImNhrFwZQK3YHpwPwDpt5A4bFTxsDu2o8U0yc+X50+M3Bi53C0sOHjiOCStG/Bp1nfowHQBgUFCETp4G3fpLAl7eWynqqu6gInjHQeNMbBz1wvRhSiXoMB2lJm8b9fLuzDuQQRFZPqD356kgTKnBM+lju4HE4zMjAT8jMam5Z4EnmaRfX7kYDGzga+PgbkkGon354i3CRhuRWtpvQeXnmjZq8MpfDC6//L7I/vvw4/LMJhiQJkXUbGEgSok8yg6jZzGx+bllc+qn7DH5nkNZKkOnqaeJHbEktgdhua/QXJcRR/5Lm0Y8ovs54A== 解密结果:>>> hell worldhell worldhell worldhell worldhell worldhell worldhell worldhell worldhell worldhell worldhell worldhell worldhell worldhell worldhell worldhell worldhell worldhell worldhell world 签名结果:>>> VinHhT+iJfDvIgseJ0ZsmJcLk+yDdx0323B6vMKMUHDlUF2HDWqQhEEoqmSstjsSfR/T+4829t5DhtaJ5w1O7K7ZyP/+yu/lupc8apmfYSIziozi3vPy20p/CYNaXAy0LLGOwrtVNn3jTaq7Gb0yI4/Zhin2jNmTk09g8Qx9rGI= 验签结果:>>> True
# -*- coding: UTF-8 -*- # ! /usr/bin/env python import base64 import M2Crypto from M2Crypto import EVP # 使用 M2Crypto库进行RSA签名和加解密 class RsaUtil(object): PUBLIC_KEY_PATH = ‘/Users/anonyper/Desktop/key/company_rsa_public_key.pem‘ # 公钥 PRIVATE_KEY_PATH = ‘/Users/anonyper/Desktop/key/company_rsa_private_key.pem‘ # 私钥 # 初始化key def __init__(self, company_pub_file=PUBLIC_KEY_PATH, company_pri_file=PRIVATE_KEY_PATH): if company_pub_file: self.company_public_key = M2Crypto.RSA.load_pub_key(company_pub_file) if company_pri_file: self.company_private_key = M2Crypto.RSA.load_key(company_pri_file) def get_max_length(self, rsa_key, encrypt=True): """加密内容过长时 需要分段加密 换算每一段的长度. :param rsa_key: 钥匙. :param encrypt: 是否是加密. """ blocksize = rsa_key.__len__() / 8 reserve_size = 11 # if not encrypt: reserve_size = 0 maxlength = blocksize - reserve_size return maxlength # 加密 支付方公钥 def encrypt_by_public_key(self, encrypt_message): """使用公钥加密. :param encrypt_message: 需要加密的内容. 加密之后需要对接过进行base64转码 """ encrypt_result = b‘‘ max_length = self.get_max_length(self.company_public_key) print(max_length) while encrypt_message: input_data = encrypt_message[:max_length] encrypt_message = encrypt_message[max_length:] out_data = self.company_public_key.public_encrypt(input_data, M2Crypto.RSA.pkcs1_padding) encrypt_result += out_data encrypt_result = base64.b64encode(encrypt_result) return encrypt_result # 加密 支付方私钥 def encrypt_by_private_key(self, encrypt_message): """使用私钥加密. :param encrypt_message: 需要加密的内容. 加密之后需要对接过进行base64转码 """ encrypt_result = b‘‘ max_length = self.get_max_length(self.company_private_key) while encrypt_message: input_data = encrypt_message[:max_length] encrypt_message = encrypt_message[max_length:] out_data = self.company_private_key.private_encrypt(input_data, M2Crypto.RSA.pkcs1_padding) encrypt_result += out_data encrypt_result = base64.b64encode(encrypt_result) return encrypt_result def decrypt_by_public_key(self, decrypt_message): """使用公钥解密. :param decrypt_message: 需要解密的内容. 解密之后的内容直接是字符串,不需要在进行转义 """ decrypt_result = b"" max_length = self.get_max_length(self.company_private_key, False) decrypt_message = base64.b64decode(decrypt_message) while decrypt_message: input_data = decrypt_message[:max_length] decrypt_message = decrypt_message[max_length:] out_data = self.company_public_key.public_encrypt(input_data, M2Crypto.RSA.pkcs1_padding) decrypt_result += out_data return decrypt_result def decrypt_by_private_key(self, decrypt_message): """使用私钥解密. :param decrypt_message: 需要解密的内容. 解密之后的内容直接是字符串,不需要在进行转义 """ decrypt_result = b"" max_length = self.get_max_length(self.company_private_key, False) decrypt_message = base64.b64decode(decrypt_message) while decrypt_message: input_data = decrypt_message[:max_length] decrypt_message = decrypt_message[max_length:] out_data = self.company_private_key.private_decrypt(input_data, M2Crypto.RSA.pkcs1_padding) decrypt_result += out_data return decrypt_result # 签名 商户私钥 base64转码 def sign_by_private_key(self, message): """私钥签名. :param message: 需要签名的内容. 签名之后,需要转义后输出 """ hs = EVP.MessageDigest(‘sha1‘) hs.update(message) digest = hs.final() # digest = hashlib.sha1(message).digest() # 内容摘要的生成方法有很多种,只要签名和解签用的是一样的就可以 signature = self.company_private_key.sign(digest) # self.company_public_key.sign(digest) # 用公钥签名IDE会崩 return base64.b64encode(signature) def verify_by_public_key(self, message, signature): """公钥验签. :param message: 验签的内容. :param signature: 对验签内容签名的值(签名之后,会进行b64encode转码,所以验签前也需转码). """ hs = EVP.MessageDigest(‘sha1‘) hs.update(message) digest = hs.final() # digest = hashlib.sha1(message).digest() # 内容摘要的生成方法有很多种,只要签名和解签用的是一样的就可以 signature = base64.b64decode(signature) return self.company_public_key.verify(digest, signature) message = ‘hell worldhell worldhell worldhell worldhell worldhell worldhell worldhell worldhell worldhell worldhell worldhell worldhell worldhell worldhell worldhell worldhell worldhell worldhell world‘ print("明文内容:>>> ") print(message) rsaUtil = RsaUtil() encrypy_result = rsaUtil.encrypt_by_public_key(message) print("加密结果:>>> ") print(encrypy_result) decrypt_result = rsaUtil.decrypt_by_private_key(encrypy_result) print("解密结果:>>> ") print(decrypt_result) sign = rsaUtil.sign_by_private_key(message) print("签名结果:>>> ") print(sign) print("验签结果:>>> ") print(rsaUtil.verify_by_public_key(message, sign)) #执行结果 明文内容:>>> hell worldhell worldhell worldhell worldhell worldhell worldhell worldhell worldhell worldhell worldhell worldhell worldhell worldhell worldhell worldhell worldhell worldhell worldhell world 加密结果:>>> fu4RgyOaokEcLmA5k0otMirZoiFBDBkEgycgehEajtPU+xP7Wf5rN05kwbsDNI7/kUR5wOvS0XE8jD1nYmKv4uBWfR5Z28BHdK20uue/8zTnPgdsAmRdzA6Lb2EIk/g38o2EtRZ4jILNOdikpW0kYpYRdaJgoHTWTOlE/RL9zcVKzYELFPpWui2jZ8EVMe+6ZiPkRKCKL571f/OTb1qOdg4GTiowZCNMIknTxXawvZl9Funz7TNz0WsNDejL+r3tM8erwhE0ygIMtemOiVy8yBVsHpHPzfdlNRoXXgtgupFEgVgEOODUp9y4LzX6UDf0+i8uI7/SpyQoa9jSpcsIjA== 解密结果:>>> hell worldhell worldhell worldhell worldhell worldhell worldhell worldhell worldhell worldhell worldhell worldhell worldhell worldhell worldhell worldhell worldhell worldhell worldhell world 签名结果:>>> VinHhT+iJfDvIgseJ0ZsmJcLk+yDdx0323B6vMKMUHDlUF2HDWqQhEEoqmSstjsSfR/T+4829t5DhtaJ5w1O7K7ZyP/+yu/lupc8apmfYSIziozi3vPy20p/CYNaXAy0LLGOwrtVNn3jTaq7Gb0yI4/Zhin2jNmTk09g8Qx9rGI= 验签结果:>>> 1
def public_encrypt(self, data, padding): # type: (bytes, int) -> bytes assert self.check_key(), ‘key is not initialised‘ return m2.rsa_public_encrypt(self.rsa, data, padding) def public_decrypt(self, data, padding): # type: (bytes, int) -> bytes assert self.check_key(), ‘key is not initialised‘ return m2.rsa_public_decrypt(self.rsa, data, padding) def private_encrypt(self, data, padding): # type: (bytes, int) -> bytes assert self.check_key(), ‘key is not initialised‘ return m2.rsa_private_encrypt(self.rsa, data, padding) def private_decrypt(self, data, padding): # type: (bytes, int) -> bytes assert self.check_key(), ‘key is not initialised‘ return m2.rsa_private_decrypt(self.rsa, data, padding)
class RSA_pub(RSA): """ Object interface to an RSA public key. """ #公钥调用下面方法直接报错 def private_encrypt(self, *argv): # type: (*Any) -> None raise RSAError(‘RSA_pub object has no private key‘) #公钥调用下面方法直接报错 def private_decrypt(self, *argv): # type: (*Any) -> None raise RSAError(‘RSA_pub object has no private key‘)
原文:https://www.cnblogs.com/dingjiaoyang/p/11935586.html