利用Python实现RSA加密解密方法实例
作者:浅若清风cyf 发布时间:2023-10-07 03:10:58
标签:python,rsa,加解密
前言
加密技术在数据安全存储,数据传输中发挥着重要作用,能够保护用户隐私数据安全,防止信息窃取。RSA是一种非对称加密技术,在软件、网页中已得到广泛应用。本文将介绍RSA加密解密在python中的实现。
原则:公钥加密,私钥解密
解释:具体过程的解释请见代码前的注释
RSA加密实验基本流程:
一、选取两个大素数p、q,并计算得到n、phi_n
二、选取常用的e = 0x10001,方便将幂运算优化为左移,加快运算速度
三、计算d,使用了扩展欧几里得算法
四、输入明文a,将明文转化为可以用于计算的数字形式
五、对a使用快速幂取模,得到密文b,以16进制显示
RSA解密流程:
六、对b使用快速幂取模,得到明文a,以字符形式显示
一、安装模块
pip install pycryptodome
二、生成密钥对
密钥对文件生成和读取
代码:
from Crypto.PublicKey import RSA
def create_rsa_pair(is_save=False):
'''
创建rsa公钥私钥对
:param is_save: default:False
:return: public_key, private_key
'''
f = RSA.generate(2048)
private_key = f.exportKey("PEM") # 生成私钥
public_key = f.publickey().exportKey() # 生成公钥
if is_save:
with open("crypto_private_key.pem", "wb") as f:
f.write(private_key)
with open("crypto_public_key.pem", "wb") as f:
f.write(public_key)
return public_key, private_key
def read_public_key(file_path="crypto_public_key.pem") -> bytes:
with open(file_path, "rb") as x:
b = x.read()
return b
def read_private_key(file_path="crypto_private_key.pem") -> bytes:
with open(file_path, "rb") as x:
b = x.read()
return b
三、加密
流程:输入文本(str)→字符串编码(默认utf-8)(bytes)→rsa加密(bytes)→base64编码(bytes)→解码为字符串(str)
代码:
import base64
from Crypto.Cipher import PKCS1_v1_5
from Crypto.PublicKey import RSA
def encryption(text: str, public_key: bytes):
# 字符串指定编码(转为bytes)
text = text.encode('utf-8')
# 构建公钥对象
cipher_public = PKCS1_v1_5.new(RSA.importKey(public_key))
# 加密(bytes)
text_encrypted = cipher_public.encrypt(text)
# base64编码,并转为字符串
text_encrypted_base64 = base64.b64encode(text_encrypted ).decode()
return text_encrypted_base64
if __name__ == '__main__':
public_key = read_public_key()
text = '123456'
text_encrypted_base64 = encryption(text, public_key)
print('密文:',text_encrypted_base64)
四、解密
说明:解密流程与加密流程相反(按照加密流程逆序解密)
流程:输入文本(str)→字符串编码(默认utf-8)(bytes)→base64解码(bytes)→rsa解密(bytes)→解码为字符串(str)
代码:
import base64
from Crypto.Cipher import PKCS1_v1_5
from Crypto import Random
from Crypto.PublicKey import RSA
def decryption(text_encrypted_base64: str, private_key: bytes):
# 字符串指定编码(转为bytes)
text_encrypted_base64 = text_encrypted_base64.encode('utf-8')
# base64解码
text_encrypted = base64.b64decode(text_encrypted_base64 )
# 构建私钥对象
cipher_private = PKCS1_v1_5.new(RSA.importKey(private_key))
# 解密(bytes)
text_decrypted = cipher_private.decrypt(text_encrypted , Random.new().read)
# 解码为字符串
text_decrypted = text_decrypted.decode()
return text_decrypted
if __name__ == '__main__':
# 生成密文
public_key = read_public_key()
text = '123456'
text_encrypted_base64 = encryption(text, public_key)
print('密文:',text_encrypted_base64)
# 解密
private_key = read_private_key()
text_decrypted = decryption(text_encrypted_base64, private_key)
print('明文:',text_decrypted)
五、完整代码
import base64
from Crypto.Cipher import PKCS1_v1_5
from Crypto import Random
from Crypto.PublicKey import RSA
# ------------------------生成密钥对------------------------
def create_rsa_pair(is_save=False):
'''
创建rsa公钥私钥对
:param is_save: default:False
:return: public_key, private_key
'''
f = RSA.generate(2048)
private_key = f.exportKey("PEM") # 生成私钥
public_key = f.publickey().exportKey() # 生成公钥
if is_save:
with open("crypto_private_key.pem", "wb") as f:
f.write(private_key)
with open("crypto_public_key.pem", "wb") as f:
f.write(public_key)
return public_key, private_key
def read_public_key(file_path="crypto_public_key.pem") -> bytes:
with open(file_path, "rb") as x:
b = x.read()
return b
def read_private_key(file_path="crypto_private_key.pem") -> bytes:
with open(file_path, "rb") as x:
b = x.read()
return b
# ------------------------加密------------------------
def encryption(text: str, public_key: bytes):
# 字符串指定编码(转为bytes)
text = text.encode('utf-8')
# 构建公钥对象
cipher_public = PKCS1_v1_5.new(RSA.importKey(public_key))
# 加密(bytes)
text_encrypted = cipher_public.encrypt(text)
# base64编码,并转为字符串
text_encrypted_base64 = base64.b64encode(text_encrypted).decode()
return text_encrypted_base64
# ------------------------解密------------------------
def decryption(text_encrypted_base64: str, private_key: bytes):
# 字符串指定编码(转为bytes)
text_encrypted_base64 = text_encrypted_base64.encode('utf-8')
# base64解码
text_encrypted = base64.b64decode(text_encrypted_base64)
# 构建私钥对象
cipher_private = PKCS1_v1_5.new(RSA.importKey(private_key))
# 解密(bytes)
text_decrypted = cipher_private.decrypt(text_encrypted, Random.new().read)
# 解码为字符串
text_decrypted = text_decrypted.decode()
return text_decrypted
if __name__ == '__main__':
# 生成密钥对
# create_rsa_pair(is_save=True)
# public_key = read_public_key()
# private_key = read_private_key()
public_key, private_key = create_rsa_pair(is_save=False)
# 加密
text = '123456'
text_encrypted_base64 = encryption(text, public_key)
print('密文:', text_encrypted_base64)
# 解密
text_decrypted = decryption(text_encrypted_base64, private_key)
print('明文:', text_decrypted)
来源:https://juejin.cn/post/7083429856330907685
0
投稿
猜你喜欢
- 写入Excel中后有显示第一列客户款号总库存这些,开始写在第12行第一列开始写入,一行写入5个,然后再隔12行,再写入下边的数据,图片需要对
- 首先要扩展自带的auth_user表我就放个图吧,同时setting中应该设置:# 此处重载是为了使UserProfile生效AUTH_US
- 1**:请求收到,继续处理2**:操作成功收到,分析、接受3**:完成此请求必须进一步处理4**:请求包含一个错误语法或不能完成5**:服务
- 划动门菜单技术:运行代码框<style>body {font-size:12px;font-family:宋体}ul.TabBa
- 本文实例为大家分享了python多进程共享变量的相关代码,供大家参考,具体内容如下from multiprocessing import P
- <!--#include file="admin_Checkuser.asp"--> <%
- 批量创建文件其实很简单,只需要按照需要创建写文件、写完关闭当前写文件、创建新的写文件、写完关闭当前文件、、、不断循环即可,以下是一个简单例子
- 当遇到一个模板标签(template tag)时,模板解析器就会把标签包含的内容,以及模板解析器自己作为参数调用一个python函数。 这个
- 如果你是我的长期读者,那么你应该知道我在寻找一个完美备份程序,最后我写了一个基于bup的我自己的加密层。在写encbup的时候,我对仅仅恢复
- 判断是否xx开始使用startswith示例代码:String = "12345 上山打老虎"if str(String
- 一、route()路由概述功能:将URL绑定到函数路由函数route()的调用有两种方式:静态路由和动态路由二、静态路由和动态路径方式1:静
- 这篇文章主要介绍了微信小程序 云开发模糊查询实现详解,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友
- '定义变量 Dim cn,rs,Sql Sql = "sel
- 下午的时候,配好了OpenCV的Python环境,OpenCV的Python环境搭建。于是迫不及待的想体验一下opencv的人脸识别,如下文
- 这是我的第一个真正意思上的自动化脚本。1、练习的测试用例为:打开百度首页,搜索“胡歌”,然后检索列表,有无“胡歌的新浪微博”这个链接 2、在
- 本文实例讲述了Python定义二叉树及4种遍历方法。分享给大家供大家参考,具体如下:Python & BinaryTree1. Bi
- 在做语义分割项目时,标注的图片不合标准,而且类型是RGBA型,且是A的部分表示的类别,因此需要将该图片转化为RGB图片# -*- codin
- 阅读上一节:无序列表信息有时候是无序归纳的,有的却有着明确的顺序,在上一篇也提到了。那么简单的来想一下身边有哪些事物是有先后顺序的:操作步骤
- 简单实现了一个在函数执行出现异常时自动重试的装饰器,支持控制最多重试次数,每次重试间隔,每次重试间隔时间递增。最新的代码可以访问从githu
- 本文实例讲述了Python subprocess模块常见用法。分享给大家供大家参考,具体如下:subprocess模块是python从2.4