Key management
Generation and destruction
Generation tips:
- For symmetric encryption, use AES with at least 128 bits, preferably 256.
- Use authenticated modes if possible: GCM, CCM. If not, CTR or CBC. ECB should be avoided.
- For asymmetric encryption, use elliptic curve cryptography (ECC) like Curve25519. If not, use RSA of at least 2048 bits.
- Use safe random generators. Better CSPRNG than PRNG. In Java, always prefer SecureRandom over Random.
It is important to make the keys have a limited duration (rotate them): decrypt and re-encrypt. Key rotation is required if:
- If the previous key is known (or suspected) to have been compromised.
- When a certain predetermined time passes.
- When a certain amount of data has been encrypted.
- If the security associated with an algorithm has changed (new attacks).
Storage
Applications manage different types of secrets: credentials, encryption keys, certificate private keys, API keys, sensitive data, etc.
Secrets must be encrypted at rest and in transit. The keys to encrypt secrets are called Data Encryption Keys (DEK). These keys must also be protected, and what is done is to encrypt them using what is called Key Encryption Key (KEY) or "Master Key". This scheme makes it possible to modify the KEK while maintaining the DEK, and therefore, without requiring re-encryption of the data.
Key tips:
- If possible, never store the KEK. For example, ask for it interactively when needed.
- If feasible, use an HSM (Hardware Security Module).
- Better not to keep them in memory and plan.
- Never store them in code or git.
- DEKs and KEKs must be stored in separate locations. For example, the database and the file system, or on different machines.
- If they go to a file, protect the files with restrictive permissions.
- Do key stretching from a password to generate the KEK. For example, with the PBKDF2 key derivation function.
KeyStores
A keystore, or keystore, can have an alias, and can contain:
- Keys: Can be a key (asymmetric or symmetric). If it is asymmetric, it can contain a chain of certificates.
- Certificates: A public key, usually the root of trusted CAs.
Keystores can have different formats (JKS, JCEKS, PKCS12, PKCS11, DKS). The most used are:
- JKS (Java Key Store): Java's proprietary format. Historically, the most used. extension jks.
- PKCS#12: standard format. Recommended format. p12 or pfx extension.
Java has a tool called keytool for managing keystores. Below are some common orders.
Command to list the contents of a keystore:
$ keytool -list -v -keystore keystore.jks
Command to generate a keystore with a key pair:
$ keytool -genkey -alias mydomain -keyalg RSA -keystore keystore.jks -keysize 2048
Command to export a keystore certificate:
$ keytool -export -alias mydomain -file mydomain.crt -keystore keystore.jks
Command to import a certificate into a keystore:
$ keytool -importcert -file mydomain.crt -keystore keystore.jks -alias mydomain