Proceso
Código
import rsa
import pickle
class RsaObj(object):
"""RSA对象"""
def __init__(self):
"""初始化公钥和私钥"""
self.public_key = None
self.private_key = None
self.export_keys()
@staticmethod
def export_keys(public_key_name="public.key", private_key_name="private.key"):
"""生成新的钥匙对,导出对象到本地"""
public_key, private_key = rsa.newkeys(512)
with open(public_key_name, "wb") as public_file:
pickle.dump(public_key, public_file)
with open(private_key_name, "wb") as private_file:
pickle.dump(private_key, private_file)
@staticmethod
def load_obj_from_local(path):
"""从本地文件加载对象"""
with open(path, "rb") as f:
obj = pickle.load(f)
return obj
def load_public_key(self, public_key="public.key"):
"""加载公钥"""
self.public_key = self.load_obj_from_local(public_key)
return self.public_key
def load_private_key(self, private_key="private.key"):
"""加载私钥"""
self.private_key = self.load_obj_from_local(private_key)
return self.private_key
def load_keys(self, public_key="public.key", private_key="private.key"):
"""读取公钥和私钥, 并返回"""
self.load_public_key(public_key)
self.load_private_key(private_key)
return self.public_key, self.private_key
def rsa_encrypt(self, message_str, code='utf-8'):
"""
对传入的str字符串加密
:param message_str: 需要加密的字符串
:param code: 字符串的编码类型
:return: 返回加密的字节
"""
public_key = self.load_public_key()
content_bytes = message_str.encode(code)
print(code, content_bytes, "编码后的字节长度:{}".format(len(content_bytes)))
encrypt_content = rsa.encrypt(content_bytes, public_key)
print("加密后的内容:", encrypt_content)
print("加密后的字节数是:{}".format(len(encrypt_content)))
return encrypt_content
def rsa_decrypt(self, encrypt_bytes, code='utf-8'):
"""
使用私钥对加密的bytes进行解密
:param encrypt_bytes: 加密的内容,bytes类型
:param code: 字符串的解码类型
:return: 解密后的字符串
"""
private_key = self.load_private_key()
content_bytes = rsa.decrypt(encrypt_bytes, private_key)
decrypt_content = content_bytes.decode(code)
print("解密后的内容:", decrypt_content)
return decrypt_content
if __name__ == '__main__':
rsa_instance = RsaObj()
while True:
input_str = input("请输入需要加密的内容:")
if input_str == "exit":
exit()
encrypt_content = rsa_instance.rsa_encrypt(input_str)
content = rsa_instance.rsa_decrypt(encrypt_content)
resultado de ejecución