Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Chiffrement asymétrique (RSA) et symétrique (AES) avec PyCryptodome et Fernet

Chiffrement asymétrique (RSA) et symétrique (AES) avec PyCryptodome et Fernet

Installer les modules nécessaires

pip install pycryptodome

pip install cryptography

RSA: Encrypt / Decrypt

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

key = RSA.generate(2048)

pub = PKCS1_OAEP.new(key.publickey())

priv = PKCS1_OAEP.new(key)

encrypted_message = pub.encrypt(b"salut")

decrypted_message = priv.decrypt(encrypted_message)

RSA: Signe / Verify

from Crypto.Signature import pkcs1_15
from Crypto.Hash import SHA256
from Crypto.PublicKey import RSA

key = RSA.generate(2048)

# sign

message = b"mon message à signer"

h = SHA256.new(message)

signature = pkcs1_15.new(key).sign(h)

# verify

h = SHA256.new(message)

try:

    pkcs1_15.new(key.publickey()).verify(h, signature)
    print("La signature est valide")

except(ValueError,TypeError):

	print("La signature est invalide.")                                                                                                                               

RSA: Export / Import Keys

from Crypto.PublicKey import RSA

key = RSA.generate(2048)

private_key = key.export_key()

file_out = open("private.pem", "wb")
file_out.write(private_key)
file_out.close()

public_key = key.publickey().export_key()

file_out = open("public.pem", "wb")
file_out.write(public_key)
file_out.close()

priv = RSA.import_key(open("private.pem").read())
pub = RSA.import_key(open("public.pem").read())

AES: Encrypt / Decrypt

from cryptography.fernet import Fernet

key = Fernet.generate_key() # print(key) pour afficher et sauvegarder votre clé.

f = Fernet(key)

m = "message à chiffrer"

e = f.encrypt(m.encode())

d = f.decrypt(e)

d = d.decode()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment