rsa公钥私钥
import rsa
import base64
# 生成公钥私钥对象
pub_key_obj, priv_key_obj = rsa.newkeys(1024)
# 转化为字符串
pub_key_str = pub_key_obj.save_pkcs1()
priv_key_str = priv_key_obj.save_pkcs1()
print('公钥:{}
私钥:{}'.format(pub_key_str, priv_key_str))
# 去掉前缀
pub_key_code = base64.standard_b64encode(pub_key_str)
priv_key_code = base64.standard_b64encode(priv_key_str)
print('公钥:{}
私钥:{}'.format(pub_key_code, priv_key_code))
# 公钥加密
def encrypt(pub_key, data):
"""
:param pub_key: 公钥
:param data: 要加密的数据,长度受rsa.newkeys(1024)影响
:return: bytes,加密后的数据
"""
key_str = base64.standard_b64decode(pub_key)
pk = rsa.PublicKey.load_pkcs1(key_str)
val = rsa.encrypt(data.encode('utf-8'), pk)
return val
pub = encrypt(pub_key_code, 'hxf')
print(pub)
# 私钥解密
def decrypt(priv_key, data):
"""
:param priv_key: 私钥
:param data: 被加密的数据
:return: str,原始数据
"""
key_str = base64.standard_b64decode(priv_key)
pk = rsa.PrivateKey.load_pkcs1(key_str)
val = rsa.decrypt(data, pk).decode('utf-8')
return val
print(decrypt(priv_key_code, pub))