Python实现RSA加密解密
作者:浅若清风cyf? 发布时间:2022-04-22 19:07:41
标签:Python,RSA,加密,解密
前言
加密技术在数据安全存储,数据传输中发挥着重要作用,能够保护用户隐私数据安全,防止信息窃取。RSA是一种非对称加密技术,在软件、网页中已得到广泛应用。本文将介绍RSA加密解密在python中的实现。
原则:公钥加密,私钥解密
解释:具体过程的解释请见代码前的注释
如果本文对您有帮助,不妨点赞、收藏、关注哟!您的支持和关注是博主创作的动力!
一、安装模块
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


猜你喜欢
- 喜欢Gucci的优雅吗?或者痴迷美国普普艺术?谷歌中国最近改版的谷歌个性化首页iGoogle集中了近1500个主题,包括近120多位全球顶级
- 图形化验证码生成和验证功能介绍在使用用户名和密码登录功能时,需要填写验证码,验证码是以图形化的方式进行获取和展示的。验证码使用原理验证码的使
- 目录前言环境依赖代码前言本文主要分享一个可以将图片或者视频模糊化的工具代码。技术路线主要是使用ffmpeg滤镜。环境依赖ffmpeg环境部署
- 前言:本篇基于Python3环境,Python2环境下的range会有所不同,但并不影响我们使用。1、range()函数是什么?range(
- 前言requests是Python发送接口请求非常好用的一个三方库,由K神编写,简单,方便上手快。但是requests发送请求是串行的,即阻
- 前言责任链模式(Chain of Responsibility Pattern)是什么?责任链模式是一种行为型模式,它允许多个对象将请求沿着
- 元组:# 元组,一种不可变的序列,在创建之后不能做任何的修改# 1.不可变# 2.用()创建元组类型,数据项用逗号来分割# 3.可以是任何的
- 长期以来我就有对几年来交互设计的心得进行总结整理的想法。回到中国来亲身体会到不少同行,主要是交互设计师和视觉设计师对于交互设计的困惑,以及其
- 本文为大家讲解了Mysql多表联合查询效率分析及优化,供大家参考,具体内容如下1. 多表连接类型1. 笛卡尔积(交叉连接) 在MySQL中可
- 12-24小时制编写一个程序,要求用户输入24小时制的时间,然后显示12小时制的时间。输入格式:输入在一行中给出带有中间的:符号(半角的冒号
- 1、引言小 * 丝:鱼哥, 都说要想代码写的溜,Lamdba不能少。小鱼:你在项目代码多写几个lamdba试试,看看架构师找不找你喝茶水。小 * 丝
- 废话不多说了,直接给大家贴代码了。-- create functioncreate function [dbo].[fnXmlToJson]
- 在操作sqlserver时候用到了substring函数 SUBSTRING ( expression, start, length ) 参
- <script> Array.prototype.swap = function(i, j) { var temp = this
- 一、需求1.获取你对象chrome前一天的浏览记录中的所有网址(url)和访问时间,并存在一个txt文件中2.将这个txt文件发送给指定的邮
- Prometheus 为开发这提供了客户端工具,用于为自己的中间件开发Exporter,对接Prometheus 。目前支持的客户端GoJa
- 昨天在看别人blog的时候发现DW有这么一个东西。叫做代码片断。我们可以将常用的css定义写一个代码片断。保存在DW中,作为公用库。当再次写
- BatchNorm2d中的track_running_stats参数如果BatchNorm2d的参数val,track_running_st
- 本文实例讲述了python实现简单的计时器功能函数。分享给大家供大家参考。具体如下:此函数通过python实现了一个简单的计时器动能:
- python2.7中 集成了json的处理(simplejson),但在实际应用中,从mysql查询出来的数据,通常有日期格式,这时候,会报