python使用RSA加密

安装

pip install pycryptodome

示例

import base64
import os

from Crypto import Random
from Crypto.PublicKey import RSA
from Crypto.Cipher import PKCS1_v1_5


class RSATool():

    def __init__(self):
        self.rsa_create_key()

    def rsa_create_key(self):
        if not os.path.exists('/home/kong/Documents/项目/RSA/private.pem') or not os.path.exists('/home/kong/Documents/项目/RSA/public.pem'):
            random_generator = Random.new().read
            rsa = RSA.generate(1024, random_generator)
            private_pem = rsa.exportKey()
            with open("/home/kong/Documents/项目/RSA/private.pem", 'wb') as f:
                f.write(private_pem)
            public_pem = rsa.publickey().exportKey()
            with open('/home/kong/Documents/项目/RSA/public.pem', 'wb') as f:
                f.write(public_pem)

    def rsa_encode(self, message=""):
        msg = message
        rsakey = RSA.importKey(open('/home/kong/Documents/项目/RSA/public.pem').read())
        cipher = PKCS1_v1_5.new(rsakey)
        cipher_text = base64.b64encode(cipher.encrypt(msg.encode('utf-8')))
        return cipher_text.decode('utf-8')

    def rsa_decode(self, cipher_text=""):
        encrypt_text = cipher_text.encode('utf-8')
        rsakey = RSA.importKey(open('/home/kong/Documents/项目/RSA/private.pem').read())
        cipher = PKCS1_v1_5.new(rsakey)
        text = cipher.decrypt(base64.b64decode(encrypt_text), '解密失败')
        return text


rsa_tool = RSATool()
cipher_text = rsa_tool.rsa_encode(message='1231')
print(cipher_text)
text = rsa_tool.rsa_decode(cipher_text=cipher_text)
print(text)

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值