python中对RSA的加密和解密

首先,生成一对密钥,并保存

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(): # 用公钥加密
with open('public.pem', 'rb') as publickfile:
p = publickfile.read()
pubkey = rsa.PublicKey.load_pkcs1(p)
original_text = 'have a good time'.encode('utf8')
crypt_text = rsa.encrypt(original_text, pubkey)
print(crypt_text)
return crypt_text # 加密后的密文


def decrypt(crypt_text): # 用私钥解密
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

print(lase_text)


if __name__ == '__main__':
crypt_text = encrypt()
lase_text = decrypt(crypt_text)

posted on 2019-12-02 18:52  不要挡着我晒太阳  阅读(2619)  评论(1编辑  收藏  举报

导航