TL;DR
This guide shows you how to encrypt user data using asymmetric encryption (public/private key pairs). This means each user has their own keys, and only they can decrypt the data intended for them. We’ll cover generating keys, encrypting data, and decrypting it – all with practical examples.
Generating Key Pairs
- Choose an Algorithm: RSA is a common choice. OpenSSL is a useful tool.
openssl genrsa -out private.pem 2048This creates a 2048-bit RSA private key file named ‘private.pem’.
- Extract the Public Key: You need both keys, but share only the public one.
openssl rsa -in private.pem -pubout -out public.pemThis creates a public key file named ‘public.pem’.
- Secure Storage: Keep your private key extremely safe! Never share it.
Encrypting Data
- Get the Recipient’s Public Key: You need the public key of the user you want to send data to.
- Use OpenSSL for Encryption:
openssl rsautl -encrypt -inkey public.pem -pubin -in message.txt -out encrypted.encReplace ‘public.pem’ with the recipient’s public key file and ‘message.txt’ with your data file.
- File Format: The output (‘encrypted.enc’) will be in a binary format.
Decrypting Data
- Use OpenSSL for Decryption: You need your private key.
openssl rsautl -decrypt -inkey private.pem -in encrypted.enc -out decrypted.txtReplace ‘private.pem’ with your private key file and ‘encrypted.enc’ with the encrypted data file.
- Verify Decryption: Check that ‘decrypted.txt’ contains the original message.
Important Considerations
- Key Length: 2048 bits is generally considered secure for RSA, but consider 3072 or 4096 bits for higher security.
- Padding Schemes: Use appropriate padding schemes (e.g., OAEP) with OpenSSL to prevent attacks.
openssl rsautl -encrypt -inkey public.pem -pubin -in message.txt -out encrypted.enc -padding oaep - Hybrid Encryption: For large files, asymmetric encryption is slow. Use a hybrid approach:
- Generate a random symmetric key (e.g., AES).
- Encrypt the data with the symmetric key.
- Encrypt the symmetric key with the recipient’s public key.
- Send both the encrypted data and the encrypted symmetric key.
- cyber security Best Practices: Regularly rotate keys, store private keys securely (e.g., using a Hardware Security Module – HSM), and follow secure coding practices.