python使用rsa非对称加密过程解析
作者:子不语332 时间:2021-06-15 00:14:51
这篇文章主要介绍了python使用rsa非对称加密过程解析,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友可以参考下
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("\n",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)
来源:https://www.cnblogs.com/steven223-z/p/12101321.html
标签:python,rsa,非,对称,加密
![](/images/zang.png)
![](/images/jiucuo.png)
猜你喜欢
sqlserver 触发器实例代码
2012-01-29 18:30:45
一个简单的ASP生成HTML分页程序
2009-07-05 18:32:00
举例详解Python中smtplib模块处理电子邮件的使用
2023-10-08 04:46:14
IE6实现min-width
2008-06-12 12:40:00
ASP 常见的连接字符串写法(access2007)
2011-03-25 10:40:00
解决jupyter notebook图片显示模糊和保存清晰图片的操作
2022-08-20 12:53:59
![](https://img.aspxhome.com/file/2023/2/76782_0s.jpg)
Python中的优先队列(priority queue)和堆(heap)
2023-11-22 05:40:03
![](https://img.aspxhome.com/file/2023/0/65900_0s.png)
Python爬虫之网络请求
2023-10-29 21:28:08
![](https://img.aspxhome.com/file/2023/2/76072_0s.png)
如何做一个文本书写器?
2010-07-12 18:58:00
简单实用的图片播放器1.0(Javascript + css )
2008-07-16 10:39:00
![](https://img.aspxhome.com/file/UploadPic/20087/16/meinv_67s.gif)
python操作csv格式文件之csv.DictReader()方法
2021-03-04 18:10:04
详解Scrapy Redis入门实战
2023-04-14 11:39:08
![](https://img.aspxhome.com/file/2023/1/76111_0s.png)
SQL 中主标识列IDENTITY使用技巧
2011-06-02 08:47:00
pandas pd.read_csv()函数中parse_dates()参数的用法说明
2023-07-22 04:51:26
![](https://img.aspxhome.com/file/2023/8/63978_0s.jpg)
sqlserver中查询横表变竖表的sql语句简析
2012-05-22 18:10:00
php curl选项列表(超详细)
2023-07-18 15:19:32
浏览器tab的设计
2008-08-11 13:03:00
![](https://img.aspxhome.com/file/UploadPic/20088/11/200881113621228s.jpg)
使用Title提升可访问性
2009-04-04 17:06:00
![](https://img.aspxhome.com/file/UploadPic/20094/4/title_blueidea-67s.png)
Python实现灰色关联分析与结果可视化的详细代码
2023-08-03 15:01:56
![](https://img.aspxhome.com/file/2023/3/61703_0s.png)
Python+Qt身体特征识别人数统计源码窗体程序(使用步骤)
2021-06-03 10:40:54
![](https://img.aspxhome.com/file/2023/5/66745_0s.jpg)