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
0
投稿
猜你喜欢
- 实验原理模拟电脑通过串口与Arduino开发板通信,并通过网页实现简单交互开发环境1、Windows102、Python3.103、Prot
- 浏览器对于CSS的支持问题落后于CSS的发展,以占有市场绝对份额的Internet Explorer来说,直到其前不久发布的第8个版本才刚刚
- 这篇文章主要介绍了通过python检测字符串的字母,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友可
- 导航设计是结构层面设计中的主要工作之一,在软件中,导航设计的好坏,直接关系到用户使用是否能够流畅。面对较复杂的导航,我们第一反应是将其简化。
- 本文将介绍如何基于Python Django实现验证码登录功能。验证码登录是一种常见的身份验证方式,它可以有效防止恶意攻击和机器人登录。本文
- 1.DNS查询过程:以查询 www.baidu.com为例(1)电脑向本地域名服务器发送解析www.baidu.com的请求(2)本地域名服
- 本文主要概括安装时提示有挂起的操作、收缩数据库、压缩数据库、转移数据库给新用户以已存在用户权限、检查备份集、修复数据库等操作技巧。1.挂起操
- 这里其实并不需要其它的什么函数来支持,只需要使用MYSQL提供的一些SQL语句就可以了。这里为了简单起见,以MYSQL的系统表USER为例,
- 题目描述1266. 访问所有点的最小时间 - 力扣(LeetCode)平面上有 n 个点,点的位置用整数坐标表示 poi
- 前言Python 这门语言最大的优点之一就是语法简洁,好的代码就像伪代码一样,干净、整洁、一目了然。但有时候我们写代码,特别是 Python
- 如何制作一个分页程序?确实,翻页程序可以相互借鉴,但具体到每一需求,还是有较大差别的。代码入下,供参考:<%language=&quo
- 本文旨在分类讲述执行计划中每一种操作的相关信息。数据访问操作 首先最基本的操作就是访问数据。这既可以通过直接访问表,也可以通过访问索引来进行
- 作为一位不懂代码的业余网页制 * 好者,常常羡慕专业程序人员在浏览器中编制出的效果超酷的一些多媒体作品。唉,无奈程序那东东,酶涩南学,非一日之
- 本文实例讲述了html静态页面调用php文件的方法。分享给大家供大家参考。具体方法如下:静态页面中看上去好像是不能直接调用php文件的,但是
- 今天同事 明城 在项目中碰到一个 BUG,代码具体如下:<!DOCTYPE html PUBLIC "-//W3C//DTD
- 一开始自学Python的numpy、pandas时候,索引和切片把我都给弄晕了,特别是numpy的切片索引、布尔索引和花式索引,简直就是大乱
- 对于在外的游子,每逢佳节倍思亲。而对于996ICU的苦逼程序猿们,最期待的莫过于各种节假日能把自己丢在床上好好休息一下了。这几天各公司都陆续
- 很多人喜欢玩抖音,我也喜欢看抖音小姐姐,可拿着手机一个个找视频太费劲。作为一个程序员,如何能在电脑前一边编程一边轻松地看抖音小姐姐呢?下面利
- 基本的网站页面设计元素布局比例统计,给大家做个参考,看看您的网站是否和下面的统计一致:标志图案:位置统计结果左上角84%右上角6%上方居中6
- 万维网联盟(W3C)发布了HTML 5规格说明书的草稿 ,这是自HTML 4在十多年前发布以来的第一个主要的修订版.在这期间,随着开发者逐渐