Python实现RSA加密解密

作者:浅若清风cyf? 时间:2022-04-22 19:07:41 

前言

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

运行:

Python实现RSA加密解密

来源:https://juejin.cn/post/7083429856330907685

标签:Python,RSA,加密,解密
0
投稿

猜你喜欢

  • PHP 面向对象程序设计(oop)学习笔记(一) - 抽象类、对象接口、instanceof 和契约式编程

    2023-11-19 20:31:59
  • python实现自动发送报警监控邮件

    2023-02-02 06:17:15
  • ASP编写完整的一个IP所在地搜索类

    2007-10-18 10:43:00
  • Linux安装Python3如何和系统自带的Python2并存

    2023-08-25 03:42:09
  • 如何实现文件上传并自动归类功能?

    2010-05-24 18:37:00
  • Python使用signal定时结束AsyncIOScheduler任务的问题

    2022-12-19 21:28:11
  • python自动发邮件库yagmail的示例代码

    2022-01-15 14:23:26
  • 解决MySQL不允许从远程访问的方法

    2010-03-18 15:39:00
  • python 简单的多线程链接实现代码

    2021-09-24 02:10:02
  • Python 200行代码实现一个滑动验证码过程详解

    2022-08-24 18:24:35
  • python实现mp3文件播放的具体实现代码

    2023-02-03 13:37:52
  • 使用python怎样产生10个不同的随机数

    2021-08-12 13:07:18
  • 微信小程序上传图片功能(附后端代码)

    2023-07-24 04:21:40
  • Pytorch之Variable的用法

    2022-01-19 04:16:39
  • keras中epoch,batch,loss,val_loss用法说明

    2021-08-11 10:56:30
  • Python代码使用 Pyftpdlib实现FTP服务器功能

    2022-02-11 16:40:55
  • selenium+python自动化测试之页面元素定位

    2021-09-30 18:08:55
  • 详解django中自定义标签和过滤器

    2021-02-16 19:43:38
  • 使用Fabric自动化部署Django项目的实现

    2022-09-05 22:00:33
  • Python中的pack和unpack的使用

    2023-08-20 05:24:33
  • asp之家 网络编程 m.aspxhome.com