#!/usr/bin/env python
# encoding: utf-8
'''
@author: wk
@contact: 841169871@qq.com
@file: rsa.py
@time: 2019/11/22 15:18
@desc:
pip install pycryptodomex
'''
import binascii
from Cryptodome.PublicKey import RSA
from Cryptodome.Cipher import PKCS1_v1_5
class RsaCrypto():
def create_rsa_key(self):
'''生成RSA秘钥对'''
try:
key = RSA.generate(2048)
encrypted_key = key.exportKey(pkcs=8)
public_key = key.publickey().exportKey().decode('utf-8')
private_key = encrypted_key.decode('utf-8')
return {'state': "success", 'message': {'public_key': public_key, 'private_key': private_key}}
except Exception as err:
return {'state': "fail", 'message': str(err)}
def encrypt(self, public_key, plaintext):
'''加密方法'''
try:
recipient_key = RSA.import_key(public_key)
cipher_rsa = PKCS1_v1_5.new(recipient_key)
en_data = cipher_rsa.encrypt(plaintext.encode('utf-8'))
hex_data = binascii.hexlify(en_data).decode('utf-8')
return {'state': "success", 'message': hex_data}
except Exception as err:
return {'state': 0, 'message': str(err)}
def decrypt(self, private_key, hex_data):
'''解密方法'''
try:
private_key = RSA.import_key(private_key)
cipher_rsa = PKCS1_v1_5.new(private_key)
en_data = binascii.unhexlify(hex_data.encode('utf-8'))
data = cipher_rsa.decrypt(en_data, None).decode('utf-8')
return {'state': "success", 'message': data}
except Exception as err:
return {'state': "fail", 'message': str(err)}
if __name__ == '__main__':
r1 = RsaCrypto()
with open("D:/id_rsa","r",encoding="utf-8") as f:
line_list=f.readlines()
private_key="".join(line_list)
with open("D:/id_rsa.pub","r",encoding="utf-8") as f:
line_list=f.readlines()
public_key="".join(line_list)
enstr=r1.encrypt(public_key,"123.wukang.com")['message'] #使用公钥加密
print(enstr) #加密后的串
print(r1.decrypt(r1.private_key, enstr)['message']) #使用私钥解密