这篇文章给大家介绍rsa非对称加密如何在python项目中使用,内容非常详细,感兴趣的小伙伴们可以参考借鉴,希望对大家能有所帮助。
<强> 1,安装rsa 强>
支持python 2.7或者python 3.5以上版本
使用豆瓣pypi源来安装rsa
pip install 小姐;https://pypi.douban.com/simple , rsa
import rsa #,1,接收者(A)生成512位公私钥对 #,一只lemon_pub为PublicKey对象,,lemon_priv为PrivateKey对象 #,b只512为秘钥的位数,,可以自定义指定,,例如:128256512、1024、2048等 lemon_pub, lemon_priv =, rsa.newkeys (512)
此时的状态
#, 2,发送者(B)使用接收者(A)的公钥去加密消息 #,rsa只能处理字节类型,,故字符串类型需要转化为字节类型 时间=love_talk “Lemon  little 女孩,,小姐:love 你非常!“.encode (“utf-8") 时间=cryto_info rsa.encrypt (love_talk, lemon_pub),, #,使用接收者(A)的公钥加密
此时状态
#, 3只接收者(A)使用自己的私钥去解密消息 时间=talk_real rsa.decrypt (cryto_info, lemon_priv) 时间=talk_real2 talk_real.decode (“utf-8") 打印(talk_real2)
import rsa #,生成密钥 pubkey, privkey =, rsa.newkeys (512) #,保存密钥 打印(“==============保存密钥===============? with 开放(& # 39;public.pem& # 39;,, & # 39; w + & # 39;), as f: .decode f.write才能(pubkey.save_pkcs1 () ()) with 开放(& # 39;private.pem& # 39;,, & # 39; w + & # 39;), as f: .decode f.write才能(privkey.save_pkcs1 () ()) #导入密钥 with 开放(& # 39;public.pem& # 39;,, & # 39; " # 39;), as f: 时间=pubkey 才能;rsa.PublicKey.load_pkcs1 (f.read () .encode ()) with 开放(& # 39;private.pem& # 39;,, & # 39; " # 39;), as f: 时间=privkey 才能;rsa.PrivateKey.load_pkcs1 (f.read () .encode ()) “““ 加密RSA “““ def rsa_encrypt(信息): 时间=crypto_email_text 才能;rsa.encrypt (message.encode (),, pubkey) return crypto_email_text才能 时间=text rsa_encrypt (“first test rsa") 打印(文本) “““ 解密 “““ def rsa_decrypt(信息): 时间=message_str 才能;rsa.decrypt(消息,privkey) .decode () return message_str才能 newmessage=rsa_encrypt(“哈哈,one two  three four 微笑!“) 时间=message rsa_decrypt (newmessage) 打印(“\ n",消息) “““ 签名 “““ 时间=message & # 39;这是重要指令:…& # 39; 时间=crypto_email_text rsa.sign (message.encode (),, privkey,, & # 39; sha - 1 # 39;) “““ 验证 “““ #,收到指令明文,密文,然后用公钥验证,进行身份确认 rsa.verify (message.encode (),, crypto_email_text,, pubkey)
<强> 4,加密过程的封装强>
#,导入base64模块来进行base64编码 import base64 rsa import class HandleSign: #,才能定义服务器公钥,,往往可以存放在公钥文件中 server_pub =,才能“““ ,,,- - - - - -BEGIN PUBLIC 关键- - - - - - ,,MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQDQENQujkLfZfc5Tu9Z1LprzedE ,,,O3F7gs + 7 bzrgpsml29lemonpyvig8c604cprlittlenjpnhwu2lgirlwzylq6sbr ,,,tuPorOc42 + gInFfyhJAwdZB6Sqlove7bW + jNe5youDtU7very6Gx + muchGo8Dg + S ,,kKlZFc8Br7SHtbL2tQIDAQAB ,,,- - - - -最终获得;PUBLIC 关键- - - - - - ,,,,,, @classmethod才能 def 才能to_encrypt (cls,味精、,pub_key=None): ,,,,,, ,,,非对称加密 ,,,:param 味精:,待加密字符串或者字节 ,,,:param pub_key:,公钥 ,,,::返回,base64密文字符串 ,,,,,, ,,,if isinstance(味精,str):,,,,,, #,如果味精为字符串,,则转化为字节类型 ,,,,,msg =, msg.encode (& # 39; utf - 8 # 39;) ,,,elif isinstance(味精,字节):,,,,#,如果味精为字节类型,,则无需处理 ,,,,, 其他,,,,,,,,,,,,,,,,,,,,#,否则抛出异常 ,,,,,raise TypeError(& # 39;味精必须为字符串或者字节类型! & # 39;) null null null null null null null null null null null null null null null null null null null null null null null null null null null null null nullrsa非对称加密如何在python项目中使用