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输出一个杨辉三角的例子
Jun 13 Python
浅谈Python程序与C++程序的联合使用
Apr 07 Python
Python松散正则表达式用法分析
Apr 29 Python
Python实现好友全头像的拼接实例(推荐)
Jun 24 Python
python实现批量修改文件名代码
Sep 10 Python
python实现机械分词之逆向最大匹配算法代码示例
Dec 13 Python
Python实现的朴素贝叶斯算法经典示例【测试可用】
Jun 13 Python
在python带权重的列表中随机取值的方法
Jan 23 Python
python实现图片中文字分割效果
Jul 22 Python
简单了解Python3 bytes和str类型的区别和联系
Dec 19 Python
tensorflow模型文件(ckpt)转pb文件的方法(不知道输出节点名)
Apr 22 Python
Python中zip函数如何使用
Jun 04 Python
Python识别花卉种类鉴定网络热门植物并自动整理分类
请求模块urllib之PYTHON爬虫的基本使用
用Python仅20行代码编写一个简单的端口扫描器
Python实现视频自动打码的示例代码
Apr 08 #Python
Python OpenCV实现图形检测示例详解
Python语法学习之进程的创建与常用方法详解
基于PyQt5制作一个群发邮件工具
You might like
PHP实现CSV文件的导入和导出类
2015/03/24 PHP
PHP实现HTTP断点续传的方法
2015/06/17 PHP
ExtJS 入门
2010/10/29 Javascript
javascript实现div的显示和隐藏的小例子
2013/06/25 Javascript
微信小程序 地图定位简单实例
2016/10/14 Javascript
详解Javascript几种跨域方式总结
2017/02/27 Javascript
vue-music关于Player播放器组件详解
2017/11/28 Javascript
node.js中axios使用心得总结
2017/11/29 Javascript
jQuery实现右侧抽屉式在线客服功能
2017/12/25 jQuery
vue实现城市列表选择功能
2018/07/16 Javascript
Vue 项目分环境打包的方法示例
2018/08/03 Javascript
Vuex,iView UI面包屑导航使用扩展详解
2019/11/04 Javascript
Vue两个版本的区别和使用方法(更深层次了解)
2020/02/16 Javascript
ES6 Generator基本使用方法示例
2020/06/06 Javascript
JavaScript 声明私有变量的两种方式
2021/02/05 Javascript
Python numpy.array()生成相同元素数组的示例
2018/11/12 Python
Python常见的pandas用法demo示例
2019/03/16 Python
django celery redis使用具体实践
2019/04/08 Python
python获取点击的坐标画图形的方法
2019/07/09 Python
python实现IOU计算案例
2020/04/12 Python
python实现贪吃蛇双人大战
2020/04/18 Python
Matplotlib 绘制饼图解决文字重叠的方法
2020/07/24 Python
Python爬虫代理池搭建的方法步骤
2020/09/28 Python
HTML5中的nav标签学习笔记
2016/06/24 HTML / CSS
分享一个H5原生form表单的checkbox特效代码
2018/02/26 HTML / CSS
美国求婚钻戒网站:Super Jeweler
2016/08/27 全球购物
百联网上商城:i百联
2017/01/28 全球购物
给幼儿园老师的表扬信
2014/01/19 职场文书
电子信息工程专业推荐信
2014/02/14 职场文书
《埃及的金字塔》教学反思
2014/04/07 职场文书
2014房屋登记授权委托书
2014/10/13 职场文书
见义勇为事迹材料
2014/12/24 职场文书
2015年教务主任工作总结
2015/07/22 职场文书
2019预备党员转正申请书模板2篇!
2019/08/07 职场文书
Filebeat 采集 Nginx 日志的方法
2021/03/31 Servers
分享python函数常见关键字
2022/04/26 Python