Skip to content

Instantly share code, notes, and snippets.

@nkhil
Created June 6, 2022 20:27
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save nkhil/53b979e92ee2ab05fcd356295d643efe to your computer and use it in GitHub Desktop.
Save nkhil/53b979e92ee2ab05fcd356295d643efe to your computer and use it in GitHub Desktop.
Symmetric decryption using nodejs

Symmetric decryption using Nodejs

This is a working example of symmetric encryption in nodejs.

From https://stackoverflow.com/questions/41043878/symmetric-encryption-with-nodejs

var assert = require('assert');
var crypto = require('crypto');
const fs = require('fs')
const path = require('path')

var algorithm = 'aes256';
var inputEncoding = 'utf8';
var outputEncoding = 'hex';
var ivlength = 16  // AES blocksize

const key = crypto.randomBytes(32)
var iv = crypto.randomBytes(ivlength)

const filePath = path.join(__dirname, 'test/test-files/post_01.md')
const text = fs.readFileSync(filePath)

var cipher = crypto.createCipheriv(algorithm, key, iv);
var ciphered = cipher.update(text, inputEncoding, outputEncoding);
ciphered += cipher.final(outputEncoding);
var ciphertext = iv.toString(outputEncoding) + ':' + ciphered

var components = ciphertext.split(':');
var iv_from_ciphertext = Buffer.from(components.shift(), outputEncoding);
var decipher = crypto.createDecipheriv(algorithm, key, iv_from_ciphertext);
var deciphered = decipher.update(components.join(':'), outputEncoding, inputEncoding);
deciphered += decipher.final(inputEncoding);

console.log('deciphered!! \n', deciphered)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment