python in for RSA encryption and decryption

First, a pair of keys, and save

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)


Information is encrypted and decryption process:

def encrypt (): # encrypted with the public
with Open ( 'public.pem', 'RB') AS publickfile:
P = publickfile.read ()
pubkey = rsa.PublicKey.load_pkcs1 (P)
original_text = 'have have A Good Time '.encode (' UTF8 ')
crypt_text = rsa.encrypt (original_text, pubkey)
Print (crypt_text)
return the # crypt_text ciphertext encrypted


def decrypt (crypt_text): # decrypted with the private key
with open (' private.pem ', 'RB') AS privatefile:
P = privatefile.read ()
privKey = rsa.PrivateKey.load_pkcs1 (P)
lase_text = rsa.decrypt (crypt_text, privKey) .decode () # Note that this type of bytes if the result is, it is necessary for decode () into STR

Print (lase_text)


IF the __name__ == '__main__':
crypt_text = the encrypt ()
lase_text = the decrypt (crypt_text)

Guess you like

Origin www.cnblogs.com/miaoweiye/p/11972621.html