#
#
#
import logging
from Crypto.PublicKey import RSA
from Crypto.Cipher import PKCS1_v1_5

print ("Generating keys...")

msg = 'attack at dawn'
key = RSA.generate(4096)    # I know this is a huge overkill
pubkey = RSA.importKey(key.publickey().exportKey('DER'))
privkey = RSA.importKey(key.exportKey('DER'))

cipher = PKCS1_v1_5.new(pubkey)
ciphertext = cipher.encrypt(msg.encode())

print("text: {}".format(msg))
print("crypt: {}".format(ciphertext))

# decrypt(self, ct, sentinel)
# ct== cypher text, b'text as bytes'
# sentinel== object to be return on error
# https://pythonhosted.org/pycrypto/Crypto.Cipher.PKCS1_v1_5.PKCS115_Cipher-class.html#encrypt
dcipher = PKCS1_v1_5.new(privkey)
secret = dcipher.decrypt(ciphertext, 'ERROR: decrypting')
print("text: {}".format(secret))


#
# exportKey() documentation says, "construct a new key carrying only the public info"
#   testing that a new key isn't created, key should be the same
#
print("\n\n")
print("***   ***   ***   ***")
print("*** Key Gen Test  ***")
print("***   ***   ***   ***")

print("*** NEW PUB KEY:")
print("{}\n".format(key.publickey().exportKey('PEM')))

print("*** NEW PUB KEY:")
print("{}\n".format(key.publickey().exportKey('PEM')))

print("*** PRIV KEY:")
print("{}\n".format(key.exportKey('PEM')))
