What Is Symmetric Encryption: Simple Explanation and Example
key is used to both lock (encrypt) and unlock (decrypt) the information. It is fast and commonly used for secure communication between trusted parties who share the secret key.How It Works
Imagine you have a locked box and a single key that can both lock and unlock it. Symmetric encryption works the same way: the sender uses a secret key to scramble the message into a coded form, and the receiver uses the same key to turn it back into the original message.
This means both sides must keep the key secret and safe. If someone else gets the key, they can read the message. The process is very fast, which makes symmetric encryption ideal for encrypting large amounts of data.
Example
This example uses Python's cryptography library to encrypt and decrypt a message with symmetric encryption using the AES algorithm.
from cryptography.hazmat.primitives.ciphers import Cipher, algorithms, modes from cryptography.hazmat.backends import default_backend import os # Generate a random 256-bit (32 bytes) key key = os.urandom(32) # Generate a random 16-byte initialization vector (IV) iv = os.urandom(16) # Create AES cipher in CBC mode cipher = Cipher(algorithms.AES(key), modes.CBC(iv), backend=default_backend()) # Encryptor and decryptor objects encryptor = cipher.encryptor() decryptor = cipher.decryptor() # Message must be padded to 16 bytes (block size) message = b'Hello, symmetric encryption!' pad_len = 16 - (len(message) % 16) padded_message = message + bytes([pad_len] * pad_len) # Encrypt the message ciphertext = encryptor.update(padded_message) + encryptor.finalize() # Decrypt the message decrypted_padded = decryptor.update(ciphertext) + decryptor.finalize() # Remove padding pad_len = decrypted_padded[-1] decrypted = decrypted_padded[:-pad_len] print('Original:', message) print('Encrypted (hex):', ciphertext.hex()) print('Decrypted:', decrypted)
When to Use
Symmetric encryption is best when two parties already share a secret key and need to exchange data quickly and securely. It is commonly used for:
- Encrypting files on your computer
- Securing data in databases
- Protecting communication inside a secure network
- Encrypting data before sending it over the internet (often combined with other methods)
Because both sides need the same key, it is less suitable for open communication where key sharing is difficult.
Key Points
- Uses one secret key for both encryption and decryption.
- Fast and efficient for large data.
- Requires secure key sharing between parties.
- Common algorithms include AES, DES, and ChaCha20.
- Often combined with asymmetric encryption for secure key exchange.