利用Python实现RSA加密解密方法实例
作者:浅若清风cyf 时间:2023-10-07 03:10:58
前言
加密技术在数据安全存储,数据传输中发挥着重要作用,能够保护用户隐私数据安全,防止信息窃取。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)
来源:https://juejin.cn/post/7083429856330907685
标签:python,rsa,加解密
0
投稿
猜你喜欢
使用virtualenv创建Python环境及PyQT5环境配置的方法
2022-12-30 06:09:26
Javascript简单实现面向对象编程继承实例代码
2024-04-19 09:50:42
asp两组字符串数据比较合并相同数据
2011-04-14 11:08:00
python扫描proxy并获取可用代理ip的实例
2023-07-29 16:42:50
python连接MySQL、MongoDB、Redis、memcache等数据库的方法
2024-01-13 15:35:25
解决使用pip安装报错:Microsoft Visual C++ 14.0 is required.
2022-05-02 14:42:15
pytorch中的squeeze函数、cat函数使用
2022-03-27 14:32:24
mysql正确安全清空在线慢查询日志slow log的流程分享
2024-01-24 12:25:48
Python个人博客程序开发实例信息显示
2022-07-06 15:31:05
python 读取txt,json和hdf5文件的实例
2022-02-18 10:43:34
Javascript图像处理—图像形态学(膨胀与腐蚀)
2024-04-23 09:27:58
详解Java数据库连接池
2024-01-12 16:06:38
Python3.8安装Pygame教程步骤详解
2022-05-11 15:26:15
python opencv实现目标区域裁剪功能
2022-07-15 19:17:56
python中requests库session对象的妙用详解
2021-10-30 14:42:58
Python dict的常用方法示例代码
2023-05-17 09:58:15
Ajax+PHP边学边练 之五 图片处理
2023-11-18 07:21:29
python学生信息管理系统实现代码
2021-07-01 03:41:18
SecureCRTSecure7.0查看连接密码的步骤
2021-01-28 07:34:14
快速了解python leveldb
2023-06-03 11:12:19