Skip to content

Instantly share code, notes, and snippets.

@chris-rock
Last active November 10, 2020 02:27
Show Gist options
  • Star 18 You must be signed in to star a gist
  • Fork 11 You must be signed in to fork a gist
  • Save chris-rock/993d8a22c7138d1f0d2e to your computer and use it in GitHub Desktop.
Save chris-rock/993d8a22c7138d1f0d2e to your computer and use it in GitHub Desktop.
Encrypt and decrypt text in nodejs
// Part of https://github.com/chris-rock/node-crypto-examples
// Nodejs encryption with CTR
var crypto = require('crypto'),
algorithm = 'aes-256-ctr',
password = 'd6F3Efeq';
function encrypt(text){
var cipher = crypto.createCipher(algorithm,password)
var crypted = cipher.update(text,'utf8','hex')
crypted += cipher.final('hex');
return crypted;
}
function decrypt(text){
var decipher = crypto.createDecipher(algorithm,password)
var dec = decipher.update(text,'hex','utf8')
dec += decipher.final('utf8');
return dec;
}
var hw = encrypt("hello world")
// outputs hello world
console.log(decrypt(hw));
@darnfish
Copy link

Is there any way to check if the decryption was successfull instead of returning a random string when it dosen't work? Thanks.

@RichAyotte
Copy link

crypto.createCipher has been deprecated. Better to use the iv variants now.

const crypto = require('crypto')
const {algorithm, iv} = require('config').crypto

module.exports = {
	decrypt({cipherText, key}) {
		const decipher = crypto.createDecipheriv(algorithm, key, iv)
		return decipher.update(cipherText, 'hex', 'utf8') + decipher.final('utf8')
	}
	, encrypt({text, key}) {
		const cipher = crypto.createCipheriv(algorithm, key, iv)
		return cipher.update(text, 'utf8', 'hex') + cipher.final('hex')
	}
}

@hemedani
Copy link

hemedani commented Feb 9, 2019

crypto.createCipher has been deprecated. Better to use the iv variants now.

const crypto = require('crypto')
const {algorithm, iv} = require('config').crypto

module.exports = {
	decrypt({cipherText, key}) {
		const decipher = crypto.createDecipheriv(algorithm, key, iv)
		return decipher.update(cipherText, 'hex', 'utf8') + decipher.final('utf8')
	}
	, encrypt({text, key}) {
		const cipher = crypto.createCipheriv(algorithm, key, iv)
		return cipher.update(text, 'utf8', 'hex') + cipher.final('hex')
	}
}

what is your const {algorithm, iv} = require('config').crypto config

@thanhnguyenio
Copy link

my service use PHP but API server user Nodejs

how to write decrypt on PHP example ,
could you help me to solve this trouble ?
thanks

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment