We can build a simple web application to encrypt and decrypt textual information that the user keys in. Remember that strong encryption should produce different outputs even given the same input.
Author : Mourya
- Objective: Implement text encryption and decryption using the AES-256-CBC algorithm in Node.js, ensuring data security and integrity.
- Importance: Securely encrypting text data is essential for protecting sensitive information from unauthorized access and ensuring privacy.
- Node.js and npm: Ensure you have Node.js and npm (Node Package Manager) installed on your system.
- You can download and install them from Node.js official website.
- Dependencies:
- crypto: This module is part of the Node.js standard library, so no additional installation is required for it.
- dotenv: This module is used to load environment variables from a .env file into process.env.
- Environment Variables: The encryption key is stored in an environment variable for security purposes. Ensure you have a .env file with the following content:
ENCRYPTION_KEY=your-32-character-long-key- IV_LENGTH: The length of the Initialization Vector (IV) is set to 16 bytes, as required by the AES-256-CBC algorithm.
Encryption Function:
- Generates a random IV.
- Creates a Cipher instance with the AES-256-CBC algorithm, the encryption key, and the IV.
- Encrypts the input text and concatenates the encrypted data with the IV.
Decryption Function:
- Splits the input text to extract the IV and encrypted data.
- Creates a Decipher instance with the AES-256-CBC algorithm, the encryption key, and the IV.
- Decrypts the encrypted data to retrieve the original text.
- Run test.js file
You should see the original text, the encrypted text, and the decrypted text printed to the console. The decrypted text should match the original text, demonstrating that the encryption and decryption functions work correctly.
