Photo by Dragonfly Ave on Unsplash

Member-only story

Hazmat, Python and RSA Encryption

Prof Bill Buchanan OBE FRSE

--

RSA has survived over 40 years and is still used in many applications. With public-key encryption, we generate a key pair: a public key and a private key. If Bob wants to encrypt something for Alice, he will use her public key to encrypt the data, and then she will use her private key to decrypt it. In this case, we will use RSA encryption and use a public key to encrypt, and a private key to decrypt. Overall, in RSA, we generate a public key (e,N) and a private key (d,N). We encrypt a message (M) with C=M^e (mod N) and decrypt to P=C^d (mod N).

The following is the code to encrypt and decrypt. Within it we encrypt with:

ciphertext = pub.encrypt(message,padding.OAEP(mgf=padding.MGF1(algorithm=hashes.SHA256()),algorithm=hashes.SHA256(),label=None))

and where we use OAEP (Optimal Asymmetric Encryption Padding) padding for the encryption process and create a SHA-256 hash. To decrypt we use the related private key, and defines the same padding and hashing methods:

plaintext = private_key.decrypt(ciphertext,padding.OAEP(mgf=padding.MGF1(algorithm=hashes.SHA256()),algorithm=hashes.SHA256(),label=None))print("\nDecrypted Message: ",plaintext.decode())

Normally, with RSA, we do not encrypt large amounts of data, and would typically use symmetric key encryption for…

--

--

No responses yet