Skip to content

Instantly share code, notes, and snippets.

@Julien00859
Last active August 25, 2018 05:08
Show Gist options
  • Save Julien00859/60ddc7480a2a55f1aff6 to your computer and use it in GitHub Desktop.
Save Julien00859/60ddc7480a2a55f1aff6 to your computer and use it in GitHub Desktop.
Asynchrone mixted cryptography built on RSA, AES, SHA-265 and JSON
from Crypto.Cipher import AES
from Crypto.Cipher import PKCS1_OAEP
from Crypto.PublicKey import RSA
from Crypto import Random
from hashlib import sha256
import base64
import json
class async():
def crypt(self, content, crypt_key, sign_key):
""" Return an all-in-one json message with:
- "message" the content AES-encrypted with a generated random key
- "key" the AES random key RSA-encrypted with the recipient's public key
- "sign" the hash of the content RSA-encrypted with the sender's private key (in fact decrypted)
"""
aes_key = Random.new().read(32)
cipher_aes = AES.new(aes_key, 3, "shitty vector 32")
cipher_rsa = PKCS1_OAEP.new(crypt_key)
message = {}
message["content"] = base64.b85encode(cipher_aes.encrypt(content.encode())).decode()
message["key"] = base64.b85encode(cipher_rsa.encrypt(aes_key)).decode()
message["sign"] = base64.b85encode(sign_key.decrypt(sha256(content.encode()).digest())).decode()
return json.dumps(message, indent=2)
def decrypt(self, json_str, decrypt_key, sign_key):
""" Return the clear message and check if it has been send correctly"""
cipher_rsa = PKCS1_OAEP.new(decrypt_key)
data = json.loads(json_str)
aes_key = cipher_rsa.decrypt(base64.b85decode(data["key"].encode()))
cipher_aes = AES.new(aes_key, 3, "shitty vector 32")
content = cipher_aes.decrypt(base64.b85decode(data["content"].encode()))
if sign_key.encode(base64.b85decode(message["sign"])) == sha256(content).digest():
return content.decode("UTF-8")
else:
raise ValueError("Wrong hash")
if __name__ == "__main__":
asc = async()
bob = RSA.generate(1024) # Sender's key
alice = RSA.generate(1024) # Recipient's key
# Bob wants to send a message to Alice
# Ask the user to write a message then use Alice's public key (to crypt the message) and Bob's Private Key (to sign the message)
crypted = asc.crypt(input("Message: "), alice.publickey(), bob)
print("Sending: " + crypted)
# Alice reviece the message from Bob
# Decrypt the message using Alice's public key and verify ths signature using Bob's pûblic key
uncrypted = asc.decrypt(crypted, alice, bob.publickey())
print("Decrypt: " + uncrypted)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment