Crypt
This code is an utility module for securely encrypting and decrypting data using the AES-256-CBC (Advanced Encryption Standard with Cipher Block Chaining mode) algorithm.
Things to Know
- AES-256-CBC:
tip
AES-256-CBC is a symmetric encryption algorithm, meaning the same key is used for both encryption and decryption.
- Requires a 256-bit (32-byte) key and a 16-byte initialization vector (IV).
- PBKDF2:
tip
PBKDF2 (Password-Based Key Derivation Function 2) is a key derivation function that generates a strong cryptographic key from a passphrase and salt.
- It strengthens the key with high iteration counts (100,000 in this case) and uses secure hashing algorithms like SHA-512.
Functions and Workflow
1. generateKey
The generateKey function is critical for deriving a strong key. It uses PBKDF2 to derive a 256-bit key from the provided passphrase and salt.
Be mindful of using high-entropy passphrases and secure salts to ensure the strength of the generated key.
- Purpose: Derives a 256-bit encryption key from a passphrase and salt.
- Parameters:
passphrase: A user-defined string (e.g., password or secret phrase).salt: A unique value to ensure the key is unpredictable and not reusable.
- Implementation:
- Uses
crypto.pbkdf2Syncwith:- Iterations: 100,000 (higher = more computationally expensive, stronger key).
- Key length: 32 bytes (256 bits).
- Hash algorithm: SHA-512 (secure and collision-resistant).
- Uses
- Output: A cryptographically strong key used for AES-256-CBC.
2. encryptData
The encryptData function encrypts plaintext using AES-256-CBC. It generates a new random IV for each encryption to ensure the ciphertext is unique, even for identical input data.
-
Purpose: Encrypts plaintext data using AES-256-CBC.
-
Parameters:
data: The plaintext string to encrypt.
-
Implementation:
- IV Generation:
- Generates a random 16-byte initialization vector (
iv) for each encryption.
- Generates a random 16-byte initialization vector (
- Cipher Creation:
- Creates an AES cipher using
crypto.createCipherivwith the derivedKEYandiv.
- Creates an AES cipher using
- Encryption:
- Encrypts the input data in two steps:
cipher.update: Encrypts the data chunk-by-chunk.cipher.final: Finalizes encryption.
- Encrypts the input data in two steps:
- Output Formatting:
- Returns the
ivand encrypted data, both encoded in Base64, concatenated with a dot (.).
- Returns the
- IV Generation:
-
Output: A string of the form:
3. decryptData
Be cautious with data integrity during decryption. If the encrypted data is tampered with, decryption will fail.
-
Purpose: Decrypts data encrypted using
encryptData. -
Parameters:
encryptedData: The encrypted string containing the IV and encrypted data in Base64 format.
-
Implementation:
- Input Splitting:
- Splits the input string into
ivand encrypted data (encStr) using the dot (.) separator. - Decodes both from Base64 to binary format.
- Splits the input string into
- Decipher Creation:
- Creates an AES decipher using
crypto.createDecipherivwith the derivedKEYand the extractediv.
- Creates an AES decipher using
- Decryption:
- Decrypts the data in two steps:
decipher.update: Processes the encrypted data.decipher.final: Finalizes decryption.
- Decrypts the data in two steps:
- Output:
- Returns the original plaintext data.
- Input Splitting:
-
Output: The decrypted plaintext.
Exports
The encryptData and decryptData functions are exported for easy use across your application, making it simple to integrate encryption and decryption features into your project.
encryptData: To encrypt plaintext.decryptData: To decrypt encrypted strings.
Use Cases
-
Secure Storage:
Always encrypt sensitive data before storing it in a database or file system to prevent unauthorized access.
- Encrypt sensitive data before storing it in a database or file system.
-
Data Transmission:
warningWhen transmitting sensitive data over networks, always use encryption to protect it from being intercepted or altered.
- Safeguard data sent over insecure networks.
-
Password Management:
tipEncrypt user credentials to securely store them, ensuring they are protected even if the database is compromised.
- Encrypt user credentials for secure storage.
Security Best Practices
-
Strong Passphrase and Salt:
tipEnsure your passphrase has high entropy and that you use a unique salt for each encryption to enhance security.
- Use a random, high-entropy passphrase and unique salt.
-
Unique IV per Encryption:
tipNever reuse an IV for encrypting different data. Always generate a new IV for each encryption operation.
- IV is randomly generated for each encryption, ensuring no repeated ciphertext for identical plaintext.
-
Secure Key Management:
warningNever hardcode sensitive keys or salts directly into your code. Use secure storage mechanisms for such secrets.
- Keep the
KEYandsaltsecret and securely stored.
- Keep the
Example
Encryption:
const encrypted = encryptData("Hello, World!");
console.log(encrypted); // Outputs: <iv_base64>.<encrypted_data_base64>
Decryption:
const decrypted = decryptData(encrypted);
console.log(decrypted); // Outputs: Hello, World!
This module provides robust cryptographic functionality for handling sensitive data.