Skip to main content

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

  1. 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).
  2. 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.pbkdf2Sync with:
      • Iterations: 100,000 (higher = more computationally expensive, stronger key).
      • Key length: 32 bytes (256 bits).
      • Hash algorithm: SHA-512 (secure and collision-resistant).
  • Output: A cryptographically strong key used for AES-256-CBC.

2. encryptData

tip

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:

    1. IV Generation:
      • Generates a random 16-byte initialization vector (iv) for each encryption.
    2. Cipher Creation:
      • Creates an AES cipher using crypto.createCipheriv with the derived KEY and iv.
    3. Encryption:
      • Encrypts the input data in two steps:
        • cipher.update: Encrypts the data chunk-by-chunk.
        • cipher.final: Finalizes encryption.
    4. Output Formatting:
      • Returns the iv and encrypted data, both encoded in Base64, concatenated with a dot (.).
  • Output: A string of the form:


3. decryptData

warning

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:

    1. Input Splitting:
      • Splits the input string into iv and encrypted data (encStr) using the dot (.) separator.
      • Decodes both from Base64 to binary format.
    2. Decipher Creation:
      • Creates an AES decipher using crypto.createDecipheriv with the derived KEY and the extracted iv.
    3. Decryption:
      • Decrypts the data in two steps:
        • decipher.update: Processes the encrypted data.
        • decipher.final: Finalizes decryption.
    4. Output:
      • Returns the original plaintext data.
  • Output: The decrypted plaintext.


Exports

tip

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

  1. 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.
  2. Data Transmission:

    warning

    When transmitting sensitive data over networks, always use encryption to protect it from being intercepted or altered.

    • Safeguard data sent over insecure networks.
  3. Password Management:

    tip

    Encrypt 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

  1. Strong Passphrase and Salt:

    tip

    Ensure 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.
  2. Unique IV per Encryption:

    tip

    Never 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.
  3. Secure Key Management:

    warning

    Never hardcode sensitive keys or salts directly into your code. Use secure storage mechanisms for such secrets.

    • Keep the KEY and salt secret and securely stored.

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.