Skip to content

Instantly share code, notes, and snippets.

@nghiaht
Last active March 11, 2022 22:11
Show Gist options
  • Save nghiaht/4b1b4f2d0832afc81ade8e5c8303dd7d to your computer and use it in GitHub Desktop.
Save nghiaht/4b1b4f2d0832afc81ade8e5c8303dd7d to your computer and use it in GitHub Desktop.
Sample codes for encrypting and decrypting by 3DES using node-forge or built-in crypto module
const crypto = require("crypto");
/**
* Encrypt 3DES using Node.js's crypto module *
* @param data A utf8 string
* @param key Key would be hashed by md5 and shorten to maximum of 192 bits,
* @returns {*} A base64 string
*/
function encrypt3DES(data, key) {
const md5Key = crypto.createHash('md5').update(key).digest("hex").substr(0, 24);
const cipher = crypto.createCipheriv('des-ede3', md5Key, '');
let encrypted = cipher.update(data, 'utf8', 'base64');
encrypted += cipher.final('base64');
return encrypted;
}
/**
* Decrypt 3DES using Node.js's crypto module
* @param data a base64 string
* @param key Key would be hashed by md5 and shorten to max 192 bits,
* @returns {*} a utf8 string
*/
function decrypt3DES(data, key) {
const md5Key = crypto.createHash('md5').update(key).digest("hex").substr(0, 24);
const decipher = crypto.createDecipheriv('des-ede3', md5Key, '');
let encrypted = decipher.update(data, 'base64', 'utf8');
encrypted += decipher.final('utf8');
return encrypted;
}
/**
* Encrypt by 3DES using node-forge
* @param input utf8 string
* @param key key is hashed by md5 and shorten to maximum 192 bits
* @returns {String} Output is a base64 string
*/
function encrypt3DES(input, key) {
var md5Key = forge.md.md5.create();
md5Key.update(key);
md5Key = md5Key.digest().toHex();
var cipher = forge.cipher.createCipher('3DES-ECB', md5Key.substring(0, 24));
cipher.start();
cipher.update(forge.util.createBuffer(Buffer.from(input, "utf8").toString("binary")));
cipher.finish();
var encrypted = cipher.output;
return Buffer.from(encrypted.getBytes(), "binary").toString("base64")
}
/**
* Decrypt by 3DES using node-forge
* @param input A base64 sring
* @param key key is hashed by md5 and shorten to maximum 192 bits
* @returns {String} A utf8 string
*/
function decrypt3DES(input, key) {
let md5Key = forge.md.md5.create();
md5Key.update(key);
md5Key = md5Key.digest().toHex();
const decipher = forge.cipher.createDecipher('3DES-ECB', md5Key.substring(0, 24));
decipher.start();
const inputEx = forge.util.createBuffer(Buffer.from(input, "base64").toString("binary"));
decipher.update(inputEx);
decipher.finish();
const decrypted = decipher.output;
return Buffer.from(decrypted.getBytes(), "binary").toString("utf8")
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment