import os
from Crypto.PublicKey import RSA
from Crypto import Random
from Crypto.Cipher import PKCS1_OAEP
from Crypto.Hash import SHA256
from Crypto.Signature import PKCS1_v1_5
from base64 import b64decode, b64encode


pub_key_contentserver = b'-----BEGIN PUBLIC KEY-----\nMIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQDYI/jGk6f0LAT2Z6AAQUR7izbi\na5O4Zzaz4WtK00jr3AqbZMVeVZAs+As5RS35PY2BlCuEEza/J5XX1tlbUhGk/Nzu\nyYqlID6ILEk9kUqh1A6EAuNVrcCL174BRLy620pU5m+E61za0tIr1lU+Jhy4ikVK\niGQ+na5a5g0kuzZTHwIDAQAB\n-----END PUBLIC KEY-----'
pub_key_own= "-----BEGIN PUBLIC KEY-----MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQCG54kIgf8wi+WLrmg0OLXTsMF7BsYjJ8+mmx1/Ml1Hts2oVoisf8iKbfcC0jWBc1aEibi7EIZK9AWEmgpIHPZpf2Ezt36KX7pjA7CDgZBye/bw+G1CaDGxrN8a18db8c16hNxHMTMiqPm7WAgoyekOzlCT6/rqF+3w2oYuGx1tmQIDAQAB-----END PUBLIC KEY-----"
priv_key_own = b"""-----BEGIN RSA PRIVATE KEY-----
MIICWwIBAAKBgQCG54kIgf8wi+WLrmg0OLXTsMF7BsYjJ8+mmx1/Ml1Hts2oVois
f8iKbfcC0jWBc1aEibi7EIZK9AWEmgpIHPZpf2Ezt36KX7pjA7CDgZBye/bw+G1C
aDGxrN8a18db8c16hNxHMTMiqPm7WAgoyekOzlCT6/rqF+3w2oYuGx1tmQIDAQAB
AoGAXPatHenHW0LseidDs8jos+p4SjlOzOcgV2VJHGAum77DVh/bq1ObdJl2wMDv
EjfTBR6K6I3onTovm0MzlqIuw2BR2HoVkY9dkmv8v6j17jEImHvXqAXr4GyhLdcl
NAG6lZ+5BAoZskDULVPSeHY04rVMvIHWAqoE4jGIbQbZOOkCQQC2XHV1KbM9VWIf
H1PkrApsBiKMDa9AXSsbolawOUmsqlG38GuFv/5E0/9dVL2kSA2hDp8WfiaIsvvM
Rhe0l+obAkEAvWE/kaUBjU6aVG8EtD+pm20biO4sA6eMydhXOiREriX2mUFRRef0
y696P2Ge6GEGYSCdjwlZy/nwROQYoGsCWwJARyoHsEQorUuvseOA0qEMpCE0xCDm
/iAdnXgZikWg6Z/Bqh1JaHWHHYb5hYt3Qi/YGbzh+l4aXYgzWQEVaSVLdwJAcjj9
hnLnhLssClELnUvomH4uZWCB25JrMDL0KXVGl2L+YWEsC+XjmBa2vRO8LJyYpGxv
m54gMw8FBAgvclIYkQJAdV52mWKano6+ikCAw1WCEp/HB5Eiz6HU6/RLOsVxN9em
cz1snA0u3qV17TrZ920gzD/2od/bzU3Hul3yDhDRgQ==
-----END RSA PRIVATE KEY-----"""


def make_key_pair_public(username):
    random_generator = Random.new().read
    priv_key = RSA.generate(1024, random_generator)
    pub_key = priv_key.publickey()
    usercardpath = "/tmp/smartcards/" + str(username) + ".txt"
    file_object = open(usercardpath, "w+")
    file_object.write(priv_key.exportKey().decode('utf-8'))
    file_object.write("\n")
    file_object.write(pub_key.exportKey().decode('utf-8'))
    file_object.close()
    return pub_key.exportKey().decode('utf-8')


def make_key_aes():
    return os.urandom(32)


def make_encrypted_key_content_server():
    random_key = make_key_aes()
    key = RSA.importKey(pub_key_contentserver)
    pub_key = key.publickey()
    encrypted_key = encrypt(random_key, pub_key)
    return encrypted_key.hex()


def decrypt(ciphertext, priv_key):
    cipher = PKCS1_OAEP.new(priv_key)
    return cipher.decrypt(ciphertext)


def encrypt(message, pub_key):
    cipher = PKCS1_OAEP.new(pub_key)
    return cipher.encrypt(message)


def sign(message, priv_key):
    priv_key = RSA.importKey(priv_key)
    signer = PKCS1_v1_5.new(priv_key)
    hash_gen = SHA256.new()
    hash_gen.update(message.encode())
    return b64encode(signer.sign(hash_gen)).decode('utf-8')


def verify(message, signature, pub_key):
    pub_key = pub_key.replace("-----BEGIN PUBLIC KEY-----", "")
    pub_key = pub_key.replace("-----END PUBLIC KEY-----", "")
    pub_key = pub_key.replace(" ", "")
    pub_key = ('\n'.join(pub_key[i:i + 64] for i in range(0, len(pub_key), 64)))
    pub_key = "-----BEGIN PUBLIC KEY-----\n" + pub_key + "\n-----END PUBLIC KEY-----"
    signature = b64decode(signature)
    pub_key = RSA.importKey(pub_key)
    verifier = PKCS1_v1_5.new(pub_key)
    hash_gen = SHA256.new(message.encode())
    return verifier.verify(hash_gen, signature)


