I am trying to encrypt and decrypt values using node inbuild module crypto. I have followed this tutorial to encrypt the data. They haven’t to gave any sample code to decrypt. When I try to use other tutorial code to decrypt the data. It not working out. Please help me out,
Code
JavaScript
x
31
31
1
const crypto = require('crypto');
2
3
// Difining algorithm
4
const algorithm = 'aes-256-cbc';
5
6
// Defining key
7
const key = crypto.randomBytes(32);
8
9
// Defining iv
10
const iv = crypto.randomBytes(16);
11
12
// An encrypt function
13
function encrypt(text) {
14
15
// Creating Cipheriv with its parameter
16
let cipher = crypto.createCipheriv(
17
'aes-256-cbc', Buffer.from(key), iv);
18
19
// Updating text
20
let encrypted = cipher.update(text);
21
22
// Using concatenation
23
encrypted = Buffer.concat([encrypted, cipher.final()]);
24
25
// Returning iv and encrypted data
26
return encrypted.toString('hex');
27
}
28
29
30
var op = encrypt("Hi Hello"); //c9103b8439f8f1412e7c98cef5fa09a1
31
Advertisement
Answer
Since you havent provided the code for decryption, Cant help you what is actually wrong you doing, apart from that you can do this to get decrypted code:
JavaScript
1
38
38
1
const crypto = require('crypto')
2
3
// Defining key
4
const key = crypto.randomBytes(32)
5
6
// Defining iv
7
const iv = crypto.randomBytes(16)
8
9
// An encrypt function
10
function encrypt(text) {
11
// Creating Cipheriv with its parameter
12
const cipher = crypto.createCipheriv('aes-256-cbc', Buffer.from(key), iv)
13
14
// Updating text
15
let encrypted = cipher.update(text)
16
17
// Using concatenation
18
encrypted = Buffer.concat([encrypted, cipher.final()])
19
20
// Returning iv and encrypted data
21
return encrypted.toString('hex')
22
}
23
24
var op = encrypt('Hi Hello')
25
console.log(op)
26
27
function decrypt(data) {
28
// Creating Decipheriv with its parameter
29
const decipher = crypto.createDecipheriv('aes-256-cbc', Buffer.from(key), iv)
30
// Updating text
31
const decryptedText = decipher.update(data, 'hex', 'utf8')
32
const finalText = decryptedText + decipher.final('utf8')
33
return finalText
34
}
35
36
var decrptedData = decrypt(op)
37
console.log(decrptedData)
38