I am newbie with JS and trying to write a simple code to encrypt and decrypt the info via Javascript, the sample code is below. It is working till the encryption, but I want to take the 'mystr' into the decryption section back, which is however not working. Any clue would be helpful, thnaks!
var crypto = require('crypto');
var mykey = crypto.createCipher('aes-256-cbc', 'mypassword');
const readline = require('readline').createInterface({
input: process.stdin,
output: process.stdout
})
readline.question(`The string to Encrypt?`, (secret) => {
var mystr = mykey.update(`${secret}`, 'utf8', 'hex')
mystr += mykey.final('hex');
console.log(`${mystr}`);
// readline.close()
//deencryption
var mykey2 = crypto.createDecipher('aes-256-cbc', 'mypassword');
var mystr2 = mykey2.update(mystr, 'hex', 'utf8');
mystr2 += mykey2.final('utf8');
console.log(`${decrypt}`);
readline.close()
})
You need to create a decipher:
var crypto = require('crypto');
const readline = require('readline').createInterface({
input: process.stdin,
output: process.stdout
})
readline.question(`The string to Encrypt?`, (secret) => {
//create cipher
var cipher = crypto.createCipher('aes-256-cbc', 'mypassword');
//encrypt string
var mystr = cipher.update(`${secret}`, 'utf8', 'hex')
mystr += cipher.final('hex');
console.log(`${mystr}`);
//create decipher
var decipher = crypto.createDecipher('aes-256-cbc', 'mypassword');
//decrypt string
var mystr2 = decipher.update(`${mystr}`, 'hex', 'utf8')
mystr2 += decipher.final('utf8');
console.log(`${mystr2}`);
readline.close()
})
For more infos look here: https://www.w3schools.com/nodejs/ref_crypto.asp
look like, it was some silly mistake after adding decipher, it is working now:) thanks all for your comments, it help me to fix it.
Here the working code:
var crypto = require('crypto');
var mykey = crypto.createCipher('aes-256-cbc', 'mypassword');
var mykey2 = crypto.createDecipher('aes-256-cbc', 'mypassword');
const readline = require('readline').createInterface({
input: process.stdin,
output: process.stdout
})
var mystr = '';
var mystr2 = '';
readline.question(`The string to Encrypt?`, (secret) => {
mystr = mykey.update(`${secret}`, 'utf8', 'hex')
mystr += mykey.final('hex');
console.log(`${mystr}`);
mystr2 = mykey2.update(mystr, 'hex', 'utf8');
mystr2 += mykey2.final('utf8');
console.log(`${mystr2}`);
readline.close()
})
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.