Link Search Menu Expand Document

Encrypt messages with cryptography

We will explore how to encrypt a message so that only the intended recipient can decrypt and read it. There are two primary methods for achieving this:

  • βš–οΈ Symmetric cryptography: In this method, the same key is used for both encryption and decryption. This approach has been used since Roman times.
  • πŸ”€ Asymmetric cryptography: This method involves two different keys, one for encryption and another for decryption.

We will focus on asymmetric cryptography. As mentioned, this involves two keys:

  • πŸ—οΈ A public key, which is available to anyone and is used for encryption.
  • πŸ”‘ A private key, which must be kept secret and is used for decryption.

First, we import the necessary modules:

from cryptography.hazmat.primitives.asymmetric import rsa, padding
from cryptography.hazmat.primitives import hashes

We generate a private key, from which the public key is derived:

private = rsa.generate_private_key(
    public_exponent=65537,
    key_size=2048)
public = private.public_key()

Next, we encrypt a message. The encrypted_message can only be decrypted by someone who possesses the corresponding private key:

message = b"Secret message from The Python Book"
encrypted = public.encrypt(
    message,
    padding.OAEP(
        mgf=padding.MGF1(algorithm=hashes.SHA256()),
        algorithm=hashes.SHA256(),
        label=None))

The person with the private key can decrypt the message:

decrypted = private.decrypt(
    encrypted,
    padding.OAEP(
        mgf=padding.MGF1(algorithm=hashes.SHA256()),
        algorithm=hashes.SHA256(),
        label=None))

print(decrypted)
# b'Secret message from The Python Book'

Modern cryptography relies heavily on the difficulty of factoring large numbers into their prime components. While it is theoretically possible to decrypt a message without the private key by trying numerous combinations, this is practically impossible due to the time it would take.

Quantum computers have the potential to break traditional encryption schemes, but post-quantum cryptography is being developed to address this challenge. However, widespread adoption is still a few years away.

✏️ Exercises:

  • Attempt to decrypt the message using a different private key and explain the outcome.