AES Encryption & Decryption in Node.js
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
I’m truly enjoying the design and layout of your blog. It’s a very easy on the eyes which
makes it much more enjoyable for me to come here and visit more often. Did
you hire out a designer to create your theme? Great work!
Attractive section of content. I just stumbled upon your web site and in accession capital
to assert that I acquire in fact enjoyed account your blog posts.
Anyway I’ll be subscribing to your feeds and even I achievement you access consistently rapidly.
continuously i used to read smaller content which as
well clear their motive, and that is also happening with this paragraph
which I am reading at this time.
Pretty! This has been an incredibly wonderful article.
Thank yyou for supplying this info.
Chck out my blog post … https://lavishtrading.com/community/profile/rochelled33743/ (lavishtrading.com)
I absolutely love yiur blog and find almost all of your post’s to be eactly
what I’m looking for. Does one offer guest writers tto write content in your case?
I wouldn’t mind composing a post or elaborating
onn most of the subjects you write regarding here.
Again, awesome web log!
My homnepage -https://jobsforseniorsathome.com/community/profile/christengodson7/ (jobsforseniorsathome.com)
Wow that was unusual. I just wrote an really long comment but after I clicked
submi my comment didn’t appear. Grrrr… well I’m not witing all that over
again. Anyhow, just wanted too say excellent blog!
My web blog – http://www.wirsindfoto.de/?option=com_k2&view=itemlist&task=user&id=229736 (http://www.wirsindfoto.de)