RSA

Lesson 33: RSA asymmetric encryption using pycryptodome

Generate public/private key pair:

from Crypto.Cipher import PKCS1_OAEP                                
from Crypto.PublicKey import RSA                                    
                                                                    
key=RSA.generate(2048)                                              
                                                                    
privkey= key.exportKey()                                            
pubkey= key.publickey().exportKey()                                 
                                                                    
with open('public.pem','wb') as f:                                  
    f.write(pubkey)

with open('private.pem','wb') as f:
    f.write(privkey)

Encrypt using others public key:

from Crypto.Cipher import PKCS1_OAEP
from Crypto.PublicKey import RSA

with open('public.pem') as f: #use others public key (not your own)
    pubkey= f.read()

key = RSA.importKey(pubkey)
cipher = PKCS1_OAEP.new(key)

with open('secret.txt') as f: #note: secret.txt max size ~245 bytes
    s=f.read().encode()

enc = cipher.encrypt(s)

with open('secret.enc','wb') as f:
    f.write(enc)

Decrypt using your own private key:

from Crypto.Cipher import PKCS1_OAEP
from Crypto.PublicKey import RSA

with open('private.pem') as f:
    privkey= f.read()

key = RSA.importKey(privkey)
cipher = PKCS1_OAEP.new(key)

with open('secret.enc','rb') as f:
    enc=f.read()

data=cipher.decrypt(enc)

with open('secret2.txt','w') as f:
    f.write(data.decode())