Introduction
Public-key cryptography, also known as asymmetric cryptography, is an encryption method that uses two mathematically related keys, one of which is kept private and the other is made public. This tutorial will show how to use public key cryptography to encrypt and decrypt a message in Python.
Step 1: Installing the required libraries
First, you'll need to install the Python 'cryptography' library. You can do this using the pip package manager:
pip install cryptography
Step 2: Generating a key pair
The first step in the encryption process is the generation of a key pair (public and private).
from cryptography.hazmat.primitives.asymmetric import rsa
from cryptography.hazmat.primitives import serialization
private_key = rsa.generate_private_key(
public_exponent=65537,
key_size=2048,
)
public_key = private_key.public_key()
Step 3: Public key serialization
The public key can be shared with anyone, so it may need to be serialized into a sharable format.
public_pem = public_key.public_bytes(
encoding=serialization.Encoding.PEM,
format=serialization.PublicFormat.SubjectPublicKeyInfo,
)
Step 4: Encryption of the message
Now that we have a public key, we can use that key to encrypt a message.
from cryptography.hazmat.primitives import hashes
from cryptography.hazmat.primitives.asymmetric import padding
message = b"A secret message"
encrypted = public_key.encrypt(
message,
padding.OAEP(
mgf=padding.MGF1(algorithm=hashes.SHA256()),
algorithm=hashes.SHA256(),
label=None
)
)
Step 5: Message decryption
Finally, we can use the private key to decrypt the message.
original_message = private_key.decrypt(
encrypted,
padding.OAEP(
mgf=padding.MGF1(algorithm=hashes.SHA256()),
algorithm=hashes.SHA256(),
label=None
)
)
print(original_message)
Conclusion
In conclusion, public key cryptography is a powerful and secure technique for ensuring that messages can be shared securely between parties. Remember that the private key must be kept secret and protected, while the public key can be freely distributed.