python RSA加密,字节格式和base64编码格式
# coding=utf-8 import rsa import base64 def create_keys(): # 生成公钥和私钥 (pubkey, privkey) = rsa.newkeys(1024) pub = pubkey.save_pkcs1() with open(‘public.pem‘, ‘wb+‘)as f: f.write(pub) pri = privkey.save_pkcs1() with open(‘private.pem‘, ‘wb+‘)as f: f.write(pri) def encrypt(content): ‘‘‘公钥加密 :param content: :return: ‘‘‘ with open(‘public.pem‘, ‘rb‘) as publickfile: p = publickfile.read() pubkey = rsa.PublicKey.load_pkcs1(p) original_text = str(content).encode() # 加密后的密文 crypt_text = rsa.encrypt(original_text, pubkey) return crypt_text # 返回的是字节。 def decrypt(crypt_text): ‘‘‘ 私钥解密 :param crypt_text: :return: ‘‘‘ with open(‘private.pem‘, ‘rb‘) as privatefile: p = privatefile.read() privkey = rsa.PrivateKey.load_pkcs1(p) lase_text = rsa.decrypt(crypt_text, privkey).decode() # 注意,这里如果结果是bytes类型,就需要进行decode()转化为str return lase_text if __name__ == ‘__main__‘: # TODO 生成 .pem 证书 #create_keys() # 生成公钥和私钥,当前目录下会生成private.pem 和public.pem # TODO 加密和解密 返回字节 encrypt_str = encrypt(‘你好中国‘) print(encrypt_str) # b"\tGu\t‘\xbcx\xd4\xbb\xd7TI\xadS\x10\x1bPj\x12G\xd4z/\xdf\xa0$\xc2\xd1.\x14rI\xe5U\xb7\xef{\x8fX\xd5\x8d%H\x14\xc5\xaa\x15\xf1\xcd\x9aNCiqo\\x8b\xe2SsZ\xa9(5\xd3\xe5G!\x82\x1d~\x04\xc0(\xe5\xa7\x85\xb7P\xd6\x8a ?j#\xae\x17\x9a\xde\xb0\xa8\x90l\xb9\xd2\xe4\xf2G}\x8eH\x7f&\xe6\xd5\xcd\xd9\x02\xb6\x86\xc4.\xbc\xf7\xca\xd8\x10\xd3\x90,\xfe#}\xec\x0bL" # # base64编码后 print(str(base64.b64encode(encrypt_str), encoding="utf-8")) # CUd1CSe8eNS711RJrVMQG1BqEkfUei/foCTC0S4UcknlVbfve49Y1Y0lSBTFqhXxzZpOQ2lxb5lPQIviU3NaqSg10+VHIYIdfgTAKOWnhbdQ1oogP2ojrhea3rCokGy50uTyR32OSH8m5tXN2QK2hsQuvPfK2BDTkCz+I33sC0w= # TODO 解密 decrypt_str = decrypt(encrypt_str) print(decrypt_str) # 你好中国 # 如果编码后解密的时候需要解码 print(bytes(base64.b64decode(str(base64.b64encode(encrypt_str), encoding="utf-8")))) # b"\tGu\t‘\xbcx\xd4\xbb\xd7TI\xadS\x10\x1bPj\x12G\xd4z/\xdf\xa0$\xc2\xd1.\x14rI\xe5U\xb7\xef{\x8fX\xd5\x8d%H\x14\xc5\xaa\x15\xf1\xcd\x9aNCiqo\\x8b\xe2SsZ\xa9(5\xd3\xe5G!\x82\x1d~\x04\xc0(\xe5\xa7\x85\xb7P\xd6\x8a ?j#\xae\x17\x9a\xde\xb0\xa8\x90l\xb9\xd2\xe4\xf2G}\x8eH\x7f&\xe6\xd5\xcd\xd9\x02\xb6\x86\xc4.\xbc\xf7\xca\xd8\x10\xd3\x90,\xfe#}\xec\x0bL"
相关推荐
singer 2020-05-30
taiyangshenniao 2019-12-26
pythonjw 2020-11-17
hedongli 2020-09-01
浪味仙 2020-08-17
IT兄弟团 2020-08-01
凉白开 2020-07-19
kjh00abc 2020-07-08
Skyline 2020-06-28
苦咖啡flask 2020-06-18
万物weiyi 2020-06-16
半纸药笺 2020-06-14
chenhaimeimeng 2020-06-13
JF0 2020-06-13
kyelu 2020-06-02
northwindx 2020-05-31
tengyuan 2020-05-30
GreatZhou 2020-05-28
coolhty 2020-05-20