#coding=utf-8
importrsaimportbase64def 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)defencrypt(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 #返回的是字节。
defdecrypt(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).de