What is Public Key Cryptography: Explanation and Examples
Public key cryptography is a method of securing communication using two keys: a public key that anyone can use to encrypt a message, and a private key that only the receiver has to decrypt it. This allows safe data exchange without sharing secret keys beforehand.How It Works
Imagine you want to send a locked box to a friend. Instead of sharing the key to the box with everyone, your friend gives you a special lock (the public key) that only they can open with their own unique key (the private key).
You put your message inside the box and lock it with the public lock. Even if someone else gets the box, they cannot open it because only your friend has the private key. This way, you can send secret messages safely over an open channel.
Public key cryptography uses math to create these two keys that work together but cannot be easily guessed from each other. This system also allows your friend to prove they sent a message by signing it with their private key, which anyone can verify with the public key.
Example
This example shows how to generate a public and private key pair, encrypt a message with the public key, and decrypt it with the private key using Python's cryptography library.
from cryptography.hazmat.primitives.asymmetric import rsa, padding from cryptography.hazmat.primitives import hashes from cryptography.hazmat.primitives import serialization # Generate private key private_key = rsa.generate_private_key(public_exponent=65537, key_size=2048) # Get public key from private key public_key = private_key.public_key() message = b'Hello, this is a secret message!' # Encrypt message with public key ciphertext = public_key.encrypt( message, padding.OAEP(mgf=padding.MGF1(algorithm=hashes.SHA256()), algorithm=hashes.SHA256(), label=None) ) # Decrypt message with private key decrypted_message = private_key.decrypt( ciphertext, padding.OAEP(mgf=padding.MGF1(algorithm=hashes.SHA256()), algorithm=hashes.SHA256(), label=None) ) print(decrypted_message.decode())
When to Use
Public key cryptography is used whenever secure communication is needed without sharing secret keys in advance. It is common in:
- Secure websites (HTTPS) to protect data between your browser and servers.
- Sending encrypted emails so only the intended recipient can read them.
- Digital signatures to verify the identity of the sender and ensure the message was not changed.
- Cryptocurrency wallets to secure transactions.
This method is ideal when you cannot meet in person to exchange keys safely or when many people need to communicate securely.
Key Points
- Uses two keys: a public key to encrypt and a private key to decrypt.
- Allows secure communication without sharing secret keys beforehand.
- Enables digital signatures for message authenticity.
- Widely used in internet security, email encryption, and cryptocurrencies.