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 相关文章推荐
Windows系统下安装Python的SSH模块教程
Feb 05 Python
菜鸟使用python实现正则检测密码合法性
Jan 05 Python
浅析python中的分片与截断序列
Aug 09 Python
通过Python爬虫代理IP快速增加博客阅读量
Dec 14 Python
python实现发送邮件及附件功能
Mar 02 Python
python3.6+opencv3.4实现鼠标交互查看图片像素
Feb 26 Python
python用户管理系统
Mar 13 Python
分享8个非常流行的 Python 可视化工具包
Jun 05 Python
wxpython布局的实现方法
Nov 01 Python
python针对Oracle常见查询操作实例分析
Apr 30 Python
python unichr函数知识点总结
Dec 16 Python
Python的logging模块基本用法
Dec 24 Python
Python识别花卉种类鉴定网络热门植物并自动整理分类
请求模块urllib之PYTHON爬虫的基本使用
用Python仅20行代码编写一个简单的端口扫描器
Python实现视频自动打码的示例代码
Apr 08 #Python
Python OpenCV实现图形检测示例详解
Python语法学习之进程的创建与常用方法详解
基于PyQt5制作一个群发邮件工具
You might like
php桌面中心(一) 创建数据库
2007/03/11 PHP
php生成二维码的几种方式整理及使用实例
2013/06/03 PHP
如何使用纯PHP实现定时器任务(Timer)
2015/07/31 PHP
Zend Framework教程之Loader以及PluginLoader用法详解
2016/03/09 PHP
Javascript YUI 读码日记之 YAHOO.util.Dom - Part.2 0
2008/03/22 Javascript
深入理解JavaScript系列(1) 编写高质量JavaScript代码的基本要点
2012/01/15 Javascript
javascript学习笔记(十五) js间歇调用和超时调用
2012/06/20 Javascript
js中判断对象是否为空的三种实现方法
2013/12/23 Javascript
jQuery选择器源码解读(五):tokenize的解析过程
2015/03/31 Javascript
JavaScript判断字符长度、数字、Email、电话等常用判断函数分享
2015/04/01 Javascript
基于JavaScript实现 网页切出 网站title变化代码
2016/04/03 Javascript
JavaScript仿百度图片浏览效果
2016/11/23 Javascript
CentOS环境中MySQL修改root密码方法
2018/01/07 Javascript
jquery判断滚动条距离顶部的距离方法
2018/09/05 jQuery
深入理解vue-class-component源码阅读
2019/02/18 Javascript
简单了解常用的JavaScript 库
2020/07/16 Javascript
vue 如何使用递归组件
2020/10/23 Javascript
Python简单实现子网掩码转换的方法
2016/04/13 Python
python通过socket实现多个连接并实现ssh功能详解
2017/11/08 Python
快速了解Python中的装饰器
2018/01/11 Python
Python socket实现简单聊天室
2018/04/01 Python
浅述python2与python3的简单区别
2018/09/19 Python
python实现自动解数独小程序
2019/01/21 Python
python实现基于朴素贝叶斯的垃圾分类算法
2019/07/09 Python
利用anaconda作为python的依赖库管理方法
2019/08/13 Python
Django ORM实现按天获取数据去重求和例子
2020/05/18 Python
美国最大的袜子制造商和零售商:Renfro Socks
2017/09/03 全球购物
美国在线健康和美容市场:Pharmapacks
2018/12/05 全球购物
全球性的在线婚纱礼服工厂:27dress.com
2019/03/21 全球购物
adidas菲律宾官网:adidas PH
2020/02/07 全球购物
中餐厅主管的职责范文
2014/02/04 职场文书
采购部长岗位职责
2014/06/13 职场文书
学校清明节活动总结
2014/07/04 职场文书
2015年新学期寄语
2015/02/26 职场文书
医务人员医德考评自我评价
2015/03/03 职场文书
地道战观后感500字
2015/06/04 职场文书