Python实现RSA加密解密

 更新时间:2022年04月14日 18:29:17   作者:浅若清风cyf   
这篇文章主要介绍了Python实现RSA加密解密,加密技术在数据安全存储,数据传输中发挥着重要作用,能够保护用户隐私数据安全,防止信息窃取。RSA是一种非对称加密技术,在软件、网页中已得到广泛应用,下面文章更多相关内容需要的小伙伴可以参考一下

前言

  • 加密技术在数据安全存储,数据传输中发挥着重要作用,能够保护用户隐私数据安全,防止信息窃取。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加密解密的文章就介绍到这了,更多相关Python RSA加解密内容请搜索脚本之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持脚本之家!

相关文章

  • Python程序暂停的正常处理方法

    Python程序暂停的正常处理方法

    这篇文章主要介绍了Python程序暂停的实现代码,非常不错,具有一定的参考借鉴价值,需要的朋友可以参考下
    2019-11-11
  • pandas数据类型之Series的具体使用

    pandas数据类型之Series的具体使用

    本文主要介绍了pandas数据类型之Series的具体使用,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习学习吧
    2022-08-08
  • 解决pyinstaller打包pyqt5的问题

    解决pyinstaller打包pyqt5的问题

    今天小编就为大家分享一篇解决pyinstaller打包pyqt5的问题,具有很好的参考价值,希望对大家有所帮助。一起跟随小编过来看看吧
    2019-01-01
  • Python实现的FTP通信客户端与服务器端功能示例

    Python实现的FTP通信客户端与服务器端功能示例

    这篇文章主要介绍了Python实现的FTP通信客户端与服务器端功能,涉及Python基于socket的端口监听、文件传输等相关操作技巧,需要的朋友可以参考下
    2018-03-03
  • 梅尔频率倒谱系数(mfcc)及Python实现

    梅尔频率倒谱系数(mfcc)及Python实现

    这篇文章主要为大家详细介绍了语音识别之梅尔频率倒谱系数及Python实现,具有一定的参考价值,感兴趣的小伙伴们可以参考一下
    2019-06-06
  • Python抓取移动App数据使用mitmweb监听请求与响应

    Python抓取移动App数据使用mitmweb监听请求与响应

    这篇文章主要介绍了Python抓取移动App数据使用mitmweb监听请求与响应,mitmproxy控制台方式、mitmdump与Python对接的方式、mitmweb可视化方式,需要的朋友可以参考一下
    2022-01-01
  • python通过配置文件共享全局变量的实例

    python通过配置文件共享全局变量的实例

    今天小编就为大家分享一篇python通过配置文件共享全局变量的实例,具有很好的参考价值,希望对大家有所帮助。一起跟随小编过来看看吧
    2019-01-01
  • scrapy-splash简单使用详解

    scrapy-splash简单使用详解

    这篇文章主要介绍了scrapy-splash简单使用详解,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习学习吧
    2021-02-02
  • python抓取多种类型的页面方法实例

    python抓取多种类型的页面方法实例

    在本篇文章里小编给大家整理的是关于python抓取多种类型的页面方法实例内容,有需要的朋友们可以学习下。
    2019-11-11
  • python安装mysql-python简明笔记(ubuntu环境)

    python安装mysql-python简明笔记(ubuntu环境)

    这篇文章主要介绍了python安装mysql-python的方法,测试环境为ubuntu,较为详细的记录了安装mysql-python过程中遇到的问题与解决方法,具有一定参考借鉴价值,需要的朋友可以参考下
    2016-06-06

最新评论