AES Encryption & Decryption in Node.js

AES Encryption & Decryption in Node.js

Featured, Javascript, Node JS, Security

Hi Coders, Today we will see how can we implement AES Encryption & Decryption in Node.js.

What is AES ?

Advanced Encryption Standard (AES) is most poweful and widely used symmetric encryption algorithm. It is widely used in payment and chatting applications.

AES performs all its computation on bytes rather than bits.

AES treats the 128 bits of a plaintext block as 16 bytes. These 16 bytes are arranged in four columns and four rows for processing as a matrix −

Unlike DES, the number of rounds in AES is variable and depends on the length of the key. AES uses 10 rounds for 128-bit keys, 12 rounds for 192-bit keys and 14 rounds for 256-bit keys. Each of these rounds uses a different 128-bit round key, which is calculated from the original AES key.

Not going deep in AES encryption . Lets discuss how we can encrypt data in node js using AES encryption.

AES Encryption & Decryption Data in Node.js

Node.js provides built-in library called crypto for cryptographic operations. We can do encryption on Streams, Strings, Arrays and Buffers.

To install crypto module use below command in your project :

npm install crypto --save

Lets see example to encrypt data using crypto module in node js. We are writing programs using typescript.

import * as crypto from "crypto";

const algorithm = 'aes-256-cbc';
const key = ''7x!A%D*G-JaNdRgUkXp2s5v8y/B?E(H+'';
const iv = crypto.randomBytes(16);

export const encryptRequest = (data: any) => {
    const cipher = crypto.createCipheriv(algorithm, key, iv);
    const encrypted = Buffer.concat([cipher.update(data), cipher.final()]);
    console.log({
        iv: iv.toString('hex'),
        content: encrypted.toString('hex')
    })
    return {
        iv: iv.toString('hex'),
        content: encrypted.toString('hex')
    };
}

You can convert the AES encrypted data in to hex or base64 to make it redable format string.

Decryption in Node.js

import * as crypto from 'crypto';

const algorithm = 'aes-256-cbc';
const key = ''7x!A%D*G-JaNdRgUkXp2s5v8y/B?E(H+'';

export const decryptRequest = (text: any) => {
    try {
        const decipher = crypto.createDecipheriv(algorithm, key, text.iv);
        const decrpyted = Buffer.concat([decipher.update(text.content, 'base64'), decipher.final()]);
        return decrpyted.toString();
    } catch (error) {

        throw error;
    }
}

You can also pipe the streams in to the encrypt function to have secure encrypted data passing through the streams.

You can also encrypt and decrypt the buffers. Just pass the buffer in place of the string when you call the function and it should work.

Encrypt and Decrypt data in Android

Below code shows if code is encrypted from Node then how to decrypt it android and how to encrypt data to decrypt it on node js

package com.digitalwealth.app.utils

import android.security.keystore.KeyProperties
import android.util.Base64
import android.util.Log
import java.security.Key
import javax.crypto.Cipher
import javax.crypto.SecretKey
import javax.crypto.spec.IvParameterSpec
import javax.crypto.spec.SecretKeySpec

object AesAlgo {
    @Throws(Exception::class)
    fun encrypt(
        plaintext: String
    ): ByteArray {
        val IV1 = "ggGGHUiDD0Qjhuvv"
        val key = "7x!A%D*G-JaNdRgUkXp2s5v8y/B?E(H+"
        val algorithm =  KeyProperties.KEY_ALGORITHM_AES + "/" + KeyProperties.BLOCK_MODE_CBC + "/" + KeyProperties.ENCRYPTION_PADDING_PKCS7;
        val aesKey: Key = SecretKeySpec(key.toByteArray(), algorithm)
        val cipher: Cipher = Cipher.getInstance(algorithm)
        val ivSpec = IvParameterSpec(IV1.toByteArray())
        cipher.init(Cipher.ENCRYPT_MODE, aesKey, ivSpec)
        val encrypted = cipher.doFinal(plaintext.toByteArray())
        Log.d("AES_decrypted", encoderfun(encrypted)!!)
        return encrypted
    }

    fun decrypt(
        plaintext: ByteArray
    ): String {
        val IV1 = "ggGGHUiDD0Qjhuvv"
        val key = "7x!A%D*G-JaNdRgUkXp2s5v8y/B?E(H+"
        val algorithm =  KeyProperties.KEY_ALGORITHM_AES + "/" + KeyProperties.BLOCK_MODE_CBC + "/" + KeyProperties.ENCRYPTION_PADDING_PKCS7;
        val aesKey: Key = SecretKeySpec(key.toByteArray(), algorithm)
        val cipher: Cipher = Cipher.getInstance(algorithm)
        val ivSpec = IvParameterSpec(IV1.toByteArray())
        // decrypt the text
        cipher.init(Cipher.DECRYPT_MODE, aesKey, ivSpec)
        val encry = decoderfun(encoderfun(plaintext)!!)
        val decrypted: String = String(cipher.doFinal(encry))
        Log.d("AES_decrypted", decrypted)
        return decrypted
    }

    fun encoderfun(decval: ByteArray?): String? {
        return Base64.encodeToString(decval, Base64.NO_WRAP)
    }

    fun decoderfun(enval: String?): ByteArray? {
        return Base64.decode(enval, Base64.NO_WRAP)
    }
}

6 comments

Leave a Reply