安装
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)