1、安装rsa
支持python 2.7 或者 python 3.5 以上版本
使用豆瓣pypi源来安装rsa
pip install -i https://pypi.douban.com/simple rsa
2、加密解密
2.1、生成公私钥对
import rsa # 1、接收者(A)生成512位公私钥对 # a. lemon_pub为PublicKey对象, lemon_priv为PrivateKey对象 # b. 512为秘钥的位数, 可以自定义指定, 例如: 128、256、512、1024、2048等 lemon_pub, lemon_priv = rsa.newkeys(512)
此时的状态
2.2、发送者加密
# 2、发送者(B)使用接收者(A)的公钥去加密消息 # rsa只能处理字节类型, 故字符串类型需要转化为字节类型 love_talk = "Lemon little girl, I love you very much!".encode("utf-8") cryto_info = rsa.encrypt(love_talk, lemon_pub) # 使用接收者(A)的公钥加密
此时状态
2.3、接收者解密
# 3. 接收者(A)使用自己的私钥去解密消息 talk_real = rsa.decrypt(cryto_info, lemon_priv) talk_real2 = talk_real.decode("utf-8") print(talk_real2)
3、其他场景加密解密
import rsa # 生成密钥 pubkey, privkey = rsa.newkeys(512) # 保存密钥 print("==============保存密钥===============") with open('public.pem' ,'w+') as f: f.write(pubkey.save_pkcs1().decode()) with open('private.pem' ,'w+') as f: f.write(privkey.save_pkcs1().decode()) #导入密钥 with open('public.pem' ,'r') as f: pubkey = rsa.PublicKey.load_pkcs1(f.read().encode()) with open('private.pem' ,'r') as f: privkey = rsa.PrivateKey.load_pkcs1(f.read().encode()) """ 加密 RSA """ def rsa_encrypt(message): crypto_email_text = rsa.encrypt(message.encode(), pubkey) return crypto_email_text text = rsa_encrypt("first test rsa") print(text) """ 解密 """ def rsa_decrypt(message): message_str = rsa.decrypt(message,privkey).decode() return message_str newmessage=rsa_encrypt("haha,one two three four smile!") message = rsa_decrypt(newmessage) print(" ",message) """ 签名 """ message = '这是重要指令:...' crypto_email_text = rsa.sign(message.encode(), privkey, 'SHA-1') """ 验证 """ # 收到指令明文、密文,然后用公钥验证,进行身份确认 rsa.verify(message.encode(), crypto_email_text, pubkey)
4、加密过程的封装
# 导入base64模块来进行base64编码 import base64 import rsa class HandleSign: # 定义服务器公钥, 往往可以存放在公钥文件中 server_pub = """ -----BEGIN PUBLIC KEY----- MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQDQENQujkLfZfc5Tu9Z1LprzedE O3F7gs+7bzrgPsMl29LemonPYvIG8C604CprLittlenJpnhWu2lGirlWZyLq6sBr tuPorOc42+gInFfyhJAwdZB6Sqlove7bW+jNe5youDtU7very6Gx+muchGo8Dg+S kKlZFc8Br7SHtbL2tQIDAQAB -----END PUBLIC KEY----- """ @classmethod def to_encrypt(cls, msg, pub_key=None): """ 非对称加密 :param msg: 待加密字符串或者字节 :param pub_key: 公钥 :return: base64密文字符串 """ if isinstance(msg, str): # 如果msg为字符串, 则转化为字节类型 msg = msg.encode('utf-8') elif isinstance(msg, bytes): # 如果msg为字节类型, 则无需处理 pass else: # 否则抛出异常 raise TypeError('msg必须为字符串或者字节类型!') if not pub_key: # 如果pub_key为空, 则使用全局公钥 pub_key = cls.server_pub.encode("utf-8") elif isinstance(pub_key, str): # 如果pub_key为字符串, 则转化为字节类型 pub_key = pub_key.encode('utf-8') elif isinstance(pub_key, bytes): # 如果msg为字节类型, 则无需处理 pass else: # 否则抛出异常 raise TypeError('pub_key必须为None、字符串或者字节类型!') public_key_obj = rsa.PublicKey.load_pkcs1_openssl_pem(pub_key) # 创建 PublicKey 对象 #2.创建 PublicKey 对象 #public_key_obj = rsa.PublicKey.load_pkcs1(pub_key) cryto_msg = rsa.encrypt(msg, public_key_obj) # 生成加密文本 cipher_base64 = base64.b64encode(cryto_msg) # 将加密文本转化为 base64 编码 return cipher_base64.decode() # 将字节类型的 base64 编码转化为字符串类型 if __name__ == '__main__': # 待加密字符串或者字节 love_talk = "Lemon little girl, I love you very much!" #1.用自己生成的publickye测试下 #lemon_pub,lemon_priv=rsa.newkeys(512) #lemon_pub2=lemon_pub.save_pkcs1() # 调用to_encrypt类方法来进行加密 cryto_info = HandleSign.to_encrypt(love_talk) print(cryto_info)