# Encryption & Decryption in NodeJS

In an era where data breaches and cyber threats are on the rise, securing sensitive information has become more crucial than ever. Whether you're storing user passwords, transmitting confidential data, or ensuring the privacy of communication, encryption plays a vital role in protecting information from unauthorized access.

**Encryption** is the process of converting plaintext data into a coded format, known as ciphertext, which is unreadable without the proper key to decode it. This ensures that even if the data is intercepted, it cannot be understood by unauthorized parties.

On the other hand, **decryption** is the reverse process, where the ciphertext is converted back into its original, readable form using the appropriate key.

Node.js, a powerful and popular JavaScript runtime, provides robust tools and libraries that make implementing encryption and decryption straightforward. Whether you're building a web application, handling sensitive data, or developing a secure communication protocol, Node.js has you covered.

In this blog series, we'll explore how to implement various encryption and decryption techniques using Node.js. We'll start with the basics of symmetric and asymmetric encryption, dive into the Node.js `crypto` module. By the end of this series, you'll have a solid understanding of how to secure data in your Node.js applications and follow best practices to keep your information safe.

Steps to setup Encryption & Decryption in NodeJS Application:

1. Import NodeJS `crypto` package like:
    
    ```javascript
    import crypto from 'crypto';
    ```
    
2. Declare a ENCRYPTION KEY like:
    
    ```javascript
    ENCRYPTION_SECRET_KEY=w8B76RFktrFhNoPBaTS7XalGlvZriizs
    ```
    
3. Create Method for Encryption:
    
    ```javascript
    // Method for Encryption.
    const encryption = (plainText) => {
        const key = crypto.createHash('sha512').update(ENCRYPTION_SECRET_KEY).digest('hex').substring(0, 32);
        const iv = crypto.createHash('sha512').update('16').digest('hex').substring(0, 16);
        const cipher = crypto.createCipheriv("aes-256-cbc", key, iv);
        return Buffer.from(
            cipher.update(JSON.stringify(plainText), 'utf8', 'hex') + cipher.final('hex')
        ).toString('base64')
    };
    ```
    
4. Create Method for Decryption:
    
    ```javascript
    // Method for Decryption.
    const decryption = (cipherText) => {
        const key = crypto.createHash('sha512').update(ENCRYPTION_SECRET_KEY).digest('hex').substring(0, 32);
        const iv = crypto.createHash('sha512').update('16').digest('hex').substring(0, 16);
        const buff = Buffer.from(cipherText, 'base64')
        const decipher = crypto.createDecipheriv("aes-256-cbc", key, iv)
        return JSON.parse(
            decipher.update(buff.toString('utf8'), 'hex', 'utf8') +
            decipher.final('utf8')
        )
    };
    ```
    
    5. Setup Calling Both Methods:
        
        ```javascript
        const plainObject = {
            name: "John Doe",
            age: 30,
            address: {
                street: "123 Main St",
                city: "New York",
                state: "NY"
            }
        };
        
        const cipherText = encryption(plainObject);
        console.log("CipherText :", cipherText);
        
        const plainText = decryption(cipherText);
        console.log("PlainText :", plainText);
        ```
        
    6. Run File: `node filename.js`
        
    7. Output:
        
        ![Output](https://cdn.hashnode.com/res/hashnode/image/upload/v1724174712199/5112b699-4b74-428e-9e5d-4232359407eb.png align="center")
        
    
    Overall Code:
    
    ```javascript
    import crypto from 'crypto';
    
    const ENCRYPTION_SECRET_KEY = "w8B76RFktrFhNoPBaTS7XalGlvZriizs";
    
    // Method for Encryption.
    const encryption = (plainText) => {
        const key = crypto.createHash('sha512').update(ENCRYPTION_SECRET_KEY).digest('hex').substring(0, 32);
        const iv = crypto.createHash('sha512').update('16').digest('hex').substring(0, 16);
        const cipher = crypto.createCipheriv("aes-256-cbc", key, iv);
        return Buffer.from(
            cipher.update(JSON.stringify(plainText), 'utf8', 'hex') + cipher.final('hex')
        ).toString('base64')
    };
    
    // Method for Decryption.
    const decryption = (cipherText) => {
        const key = crypto.createHash('sha512').update(ENCRYPTION_SECRET_KEY).digest('hex').substring(0, 32);
        const iv = crypto.createHash('sha512').update('16').digest('hex').substring(0, 16);
        const buff = Buffer.from(cipherText, 'base64')
        const decipher = crypto.createDecipheriv("aes-256-cbc", key, iv)
        return JSON.parse(
            decipher.update(buff.toString('utf8'), 'hex', 'utf8') +
            decipher.final('utf8')
        )
    };
    
    const plainObject = {
        name: "John Doe",
        age: 30,
        address: {
            street: "123 Main St",
            city: "New York",
            state: "NY"
        }
    };
    
    const cipherText = encryption(plainObject);
    console.log("CipherText :", cipherText);
    
    const plainText = decryption(cipherText);
    console.log("PlainText :", plainText);
    ```
    
    If you found this article helpful, don't forget to **follow our blog** for more insights and tips on Node.js and cybersecurity. **Like** and **share** this post with your network to spread the knowledge. Have questions or need further assistance? **Contact us** today—we're here to help!
