Python加密技术之RSA加密解密的实现


Posted in Python onApril 08, 2022

前言

  • 加密技术在数据安全存储,数据传输中发挥着重要作用,能够保护用户隐私数据安全,防止信息窃取。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)

Python加密技术之RSA加密解密的实现

总结

到此这篇关于利用Python实现RSA加密解密的文章就介绍到这了,更多相关Python RSA加密解密内容请搜索三水点靠木以前的文章或继续浏览下面的相关文章希望大家以后多多支持三水点靠木!

Python 相关文章推荐
在Python中使用matplotlib模块绘制数据图的示例
May 04 Python
Python cookbook(数据结构与算法)从任意长度的可迭代对象中分解元素操作示例
Feb 13 Python
Python运维自动化之nginx配置文件对比操作示例
Aug 29 Python
influx+grafana自定义python采集数据和一些坑的总结
Sep 17 Python
python 实现语音聊天机器人的示例代码
Dec 02 Python
python3 enum模块的应用实例详解
Aug 12 Python
Python封装成可带参数的EXE安装包实例
Aug 24 Python
python自动生成model文件过程详解
Nov 02 Python
Python中zip()函数的解释和可视化(实例详解)
Feb 16 Python
使用python实现CGI环境搭建过程解析
Apr 28 Python
Python urllib库如何添加headers过程解析
Oct 05 Python
python如何在word中存储本地图片
Apr 07 Python
Python识别花卉种类鉴定网络热门植物并自动整理分类
请求模块urllib之PYTHON爬虫的基本使用
用Python仅20行代码编写一个简单的端口扫描器
Python实现视频自动打码的示例代码
Apr 08 #Python
Python OpenCV实现图形检测示例详解
Python语法学习之进程的创建与常用方法详解
基于PyQt5制作一个群发邮件工具
You might like
PHP中图片等比缩放的实例
2013/03/24 PHP
PHP加密解密类实例分析
2015/04/20 PHP
WordPress中用于获取及自定义头像图片的PHP脚本详解
2015/12/17 PHP
thinkphp跨库操作的简单代码实例
2016/09/22 PHP
PHP实现的mysql主从数据库状态检测功能示例
2017/07/20 PHP
php实现文章评论系统
2019/02/18 PHP
分享几种好用的PHP自定义加密函数(可逆/不可逆)
2020/09/15 PHP
Jquery实现仿新浪微博获取文本框能输入的字数代码
2013/02/22 Javascript
JavaScript代码简单实现求杨辉三角给定行的最大值
2013/10/29 Javascript
js简单的弹出框有关闭按钮
2014/05/05 Javascript
基于javascript实现九九乘法表
2016/03/27 Javascript
Mvc提交表单的四种方法全程详解
2016/08/10 Javascript
js HTML5多图片上传及预览实例解析(不含前端的文件分割)
2016/08/26 Javascript
微信小程序 action-sheet底部菜单详解
2016/10/27 Javascript
jQuery的事件预绑定
2016/12/05 Javascript
ng-options和ng-checked在表单中的高级运用(推荐)
2017/01/21 Javascript
angular+webpack2实战例子
2017/05/23 Javascript
Vue学习笔记进阶篇之vue-router安装及使用方法
2017/07/19 Javascript
nodejs(officegen)+vue(axios)在客户端导出word文档的方法
2018/07/31 NodeJs
总结javascript三元运算符知识点
2018/09/28 Javascript
layui 弹出层值回传解决方式
2019/11/14 Javascript
JavaScript中clientWidth,offsetWidth,scrollWidth的区别
2021/01/25 Javascript
[00:15]TI9观赛名额抽取
2019/07/10 DOTA
python缩进区别分析
2014/02/15 Python
Python开发实例分享bt种子爬虫程序和种子解析
2014/05/21 Python
Python+AutoIt实现界面工具开发过程详解
2019/08/07 Python
win10从零安装配置pytorch全过程图文详解
2020/05/08 Python
python 负数取模运算实例
2020/06/03 Python
Pytorch - TORCH.NN.INIT 参数初始化的操作
2021/02/27 Python
HTML5调用手机发短信和打电话功能
2020/04/29 HTML / CSS
美体小铺波兰官方网站:The Body Shop波兰
2019/09/03 全球购物
理工大学毕业生自荐信范文
2014/02/22 职场文书
我们的节日春节活动方案
2014/08/22 职场文书
软件研发工程师岗位职责
2014/09/30 职场文书
证婚人致辞精选
2015/07/28 职场文书
MySQL限制查询和数据排序介绍
2022/03/25 MySQL