python使用RSA加密

安装第三方包Crypto:

pip install pycryptodome==3.10.1
import base64
from Crypto import Random
from Crypto.PublicKey import RSA
from Crypto.Cipher import PKCS1_v1_5 as Cipher_pkcs1_v1_5


class RSATool():
    """
    RSA加密是一种非对称加密,通常使用公钥加密,私钥解密,私钥签名,公钥验签。
    在公开密钥密码体制中,加密密钥(即公开密钥)PK是公开信息,而解密密钥(即秘密密钥)SK是需要保密的.
    RSA算法通常是先生成一对RSA密钥,其中之一是保密密钥,由用户保存;另一个为公开密钥,可对外公开,甚至可在网络服务器中注册。
    pip install pycryptodome==3.10.1 (Crypto)
    """

    def __init__(self):
        """RSA 生成公钥私钥"""
        self.rsa_create_key()

    # 1、生成公钥私钥
    def rsa_create_key(self):
        """RSA 生成公钥私钥"""
        # 公钥私钥不存在则创建
        if not os.path.exists("data/private.pem") or not os.path.exists("data/public.pem"):
            # 伪随机数生成器
            random_generator = Random.new().read
            # rsa算法生成实例
            rsa = RSA.generate(1024, random_generator)
            
            private_pem = rsa.exportKey() # 私钥生成并保存
            with open("data/private.pem", "wb") as f:
                f.write(private_pem)

            public_pem = rsa.publickey().exportKey() # 公钥生成并保存
            with open("data/public.pem", "wb") as f:
                f.write(public_pem)

    # 2、加密(使用公钥加密)
    def rsa_encode(message=""):
        """RSA 加密(使用公钥加密)"""
        msg = message.decode("utf-8")  # python2 中文需要decode utf8
        rsakey = RSA.importKey(open("data/public.pem").read())
        cipher = Cipher_pkcs1_v1_5.new(rsakey)  # 创建用于执行pkcs1_v1_5加密或解密的密码
        cipher_text = base64.b64encode(cipher.encrypt(msg.encode('utf-8')))
        return cipher_text.decode('utf-8')

    # 3、解密(使用私钥解密)
    def rsa_decode(cipher_text=""):
        """RSA 解密(使用私钥解密)"""
        encrypt_text = cipher_text.encode('utf-8')
        rsakey = RSA.importKey(open("data/private.pem").read())
        cipher = Cipher_pkcs1_v1_5.new(rsakey)  # 创建用于执行pkcs1_v1_5加密或解密的密码
        text = cipher.decrypt(base64.b64decode(encrypt_text), "解密失败")
        return text.decode('utf-8')

  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值