python RSA加密,字节格式和base64编码格式
2020-12-27 10:27
标签:当前目录 xca 生成 save read param utf-8 vat 目录 python RSA加密,字节格式和base64编码格式 标签:当前目录 xca 生成 save read param utf-8 vat 目录 原文地址:https://www.cnblogs.com/pythonSF/p/13032812.html# 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\x99O@\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\x99O@\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"
文章标题:python RSA加密,字节格式和base64编码格式
文章链接:http://soscw.com/index.php/essay/38561.html