Asymmetric Encryption
Asymmetric encryption is a type of encryption where a pair of keys is used to encrypt and decrypt electronic information. The key pair consists of a public key and a private key. The public key is used to encrypt the information and the private key is used to decrypt it.
Order of preference
- Well-Known Libraries
-
ECC
RSA-KEM
: RSA Key Encapsulation MechanismRSA-OAEP
: RSA Optimal Asymmetric Encryption Padding
The latter part of this document will cover the RSA encryption process, but getting RSA right is hard and SHOULD BE AVOIDED, even with the right libraries. Prefer the first two options whenever possible.
RSA Key Generation
- Storage Format
- Recommended: Encode in base64 with
PEM
format. - Alternatively, store in binary with
DER
format.
- Recommended: Encode in base64 with
- Bit length
- Recommended:
2048
bits. Good balance between security and performance. - Alternatively, consider
3072
or4096
for higher security. Note that this will slow down encryption/decryption.
- Recommended:
Private key
- PKCS#8
- PKCS#1
Recommended. More modern and flexible.
openssl genpkey -algorithm RSA -out private_key.pem -pkeyopt rsa_keygen_bits:2048
The output key header will be -----BEGIN PRIVATE KEY-----
.
Specific to RSA (Legacy)
openssl genrsa -out private_key.pem 2048
The output key header may be -----BEGIN PRIVATE KEY-----
or -----BEGIN RSA PRIVATE KEY-----
.
Public key
Public key are derived from private key.
- PKIX
- PKCS#1
Recommended. PKIX (Public Key Infrastructure) also known as X.509 or SPKI (Subject Public Key Info)
openssl rsa -pubout -in private_key.pem -out public_key.pem
Legacy format specific to RSA
openssl rsa -in private_key.pem -RSAPublicKey_out -out public_key.pem
RSA-KEM
High level overview:
- Create a random symmetric key
- Encrypt it with RSA public key
- Encrypt the data with the symmetric key
- Send the encrypted symmetric key and the encrypted data
RSA-OAEP
Hashing
SHA-256
: RecommendedSHA-1
: Cryptographically broken, and should not be used.
Padding
OAEP
: Recommended- PKCS#1 v1.5: Legacy
Label
By default the label is empty, but it can be set to a specific value. Both the encryptor and decryptor must use the same label.
☠️ AVOID THESE
RSA
in generalElGamal
OpenPGP
,OpenSSL
,BouncyCastle
, etc.