from Crypto import Random
from Crypto.PublicKey import RSA
from Crypto.Cipher import PKCS1_v1_5
import rsa as rsa_lower
# 使用公钥进行rsa加密
def rsa_encode(publicKey, content):
"""
根据 模量与指数 生成公钥,并利用公钥对内容 rsa 加密返回结果
:param e:指数
:param n: 模量
:param content:待加密字符串
:return: 加密后结果
"""
recipient_key = RSA.import_key(public_key)
cipher_rsa = PKCS1_v1_5.new(recipient_key)
m = cipher_rsa.encrypt(content.encode())
return m.hex();
# 使用指数和模数进行rsa加密
def rsa_encode_modulus(publicExponent,publicModulus,content):
"""
根据 模量与指数 生成公钥,并利用公钥对内容 rsa 加密返回结果
:param publicExponent: e 指数
:param publicModulus: n 模量
:param content:待加密字符串
:return: 加密后结果
"""
publicExponent = int(publicExponent, 16)
publicModulus = int(publicModulus, 16)
pub_key = rsa_lower.PublicKey(e=publicExponent, n=publicModulus)
m = rsa_lower.encrypt(content.encode(),pub_key)
return m.hex();
# 私钥解密
def rsa_decode(cipher_text, private_key):
rsakey = RSA.importKey(private_key) # 导入读取到的私钥
cipher = PKCS1_v1_5.new(rsakey) # 生成对象
# 将密文解密成明文,返回的是一个bytes类型数据,需要自己转换成str
# text = cipher.decrypt(base64.b64decode(cipher_text), "ERROR")
text = cipher.decrypt(bytes().fromhex(cipher_text), "ERROR")
return text.decode()
# 转换为16进制
def toHex(num):
"""
:type num: int
:rtype: str
"""
chaDic = {10: 'a', 11: 'b', 12: 'c', 13: 'd', 14: 'e', 15: 'f'}
hexStr = ""
if num < 0:
num = num + 2**32
while num >= 16:
digit = num % 16
hexStr = chaDic.get(digit, str(digit)) + hexStr
num //= 16
hexStr = chaDic.get(num, str(num)) + hexStr
return hexStr
# 获取公钥 私钥 模数 指数
def get_rsa_key():
rsaInstance = RSA.generate(1024, Random.new().read)
private_key = rsaInstance.exportKey().decode()
public_pem = rsaInstance.publickey()
public_key = rsaInstance.publickey().exportKey().decode()
publicModulus=toHex(public_pem.n)
publicExponent=toHex(public_pem.e)
return public_key,private_key,publicModulus,publicExponent
# rsa加密
public_key, private_key, publicModulus, publicExponent = get_rsa_key()
cipher_text = rsa_encode_modulus(publicExponent, publicModulus, "123456")
#cipher_text = rsa_encode(public_key,"123456")
print(cipher_text)
# rsa解密
plain_text = rsa_decode(cipher_text, private_key)
print(plain_text)
运行结果: