1import Crypto
2from Crypto.PublicKey import RSA
3from Crypto import Random
4
5random_generator = Random.new().read
6key = RSA.generate(1024, random_generator) #generate public and private keys
7
8publickey = key.publickey # pub key export for exchange
9
10encrypted = publickey.encrypt('encrypt this message', 32)
11#message to encrypt is in the above line 'encrypt this message'
12
13print 'encrypted message:', encrypted #ciphertext
14
15f = open ('encryption.txt', 'w'w)
16f.write(str(encrypted)) #write ciphertext to file
17f.close()
18
19#decrypted code below
20
21f = open ('encryption.txt', 'r')
22message = f.read()
23
24decrypted = key.decrypt(message)
25
26print 'decrypted', decrypted
27
28f = open ('encryption.txt', 'w')
29f.write(str(message))
30f.write(str(decrypted))
31f.close()
1from Crypto.PublicKey import RSA
2from Crypto.Cipher import PKCS1_OAEP
3import binascii
4
5keyPair = RSA.generate(3072)
6
7pubKey = keyPair.publickey()
8print(f"Public key: (n={hex(pubKey.n)}, e={hex(pubKey.e)})")
9pubKeyPEM = pubKey.exportKey()
10print(pubKeyPEM.decode('ascii'))
11
12print(f"Private key: (n={hex(pubKey.n)}, d={hex(keyPair.d)})")
13privKeyPEM = keyPair.exportKey()
14print(privKeyPEM.decode('ascii'))
15
16
17msg = bytes(str(input("Enter plain text: ")), 'utf-8')
18encryptor = PKCS1_OAEP.new(pubKey)
19encrypted = encryptor.encrypt(msg)
20print("Encrypted:", binascii.hexlify(encrypted))
21
22decryptor = PKCS1_OAEP.new(keyPair)
23decrypted = decryptor.decrypt(encrypted)
24print('Decrypted:', decrypted.decode('utf-8'))