Symmetrical encryption in Node.js

node v12.22.12
version: 7.0.0
endpointsharetweet
Two ways to test this: · Run the cell below to see a demo, or · cURL or browse the API endpoint: https://runkit.io/tripu/symmetrical-encryption-in-node-js/branches/master
const CRYPTO = require("crypto"); // const RND = require('randombytes-shim'); const CIPHER_ALGORITHM = 'aes-256-ctr'; const HASH = 'sha256'; const IV = new Uint8Array([255, 141, 177, 247, 66, 19, 185, 246, 81, 227, 16, 206, 6, 165, 172, 37]); // RND(16); const DEFAULT_SECRET = 'zecretPassw0rd'; const encrypt = (plain, secret = DEFAULT_SECRET) => { const KEY = CRYPTO.createHash(HASH).update(String(secret)).digest('base64').substr(0, 32); const CIPHER = CRYPTO.createCipheriv(CIPHER_ALGORITHM, KEY, IV) return CIPHER.update(plain, 'utf-8', 'hex'); }; const decrypt = (encrypted, secret = DEFAULT_SECRET) => { const KEY = CRYPTO.createHash(HASH).update(String(secret)).digest('base64').substr(0, 32); const DECIPHER = CRYPTO.createDecipheriv(CIPHER_ALGORITHM, KEY, IV) return DECIPHER.update(encrypted, 'hex', 'utf-8'); }; //------------------------------------------ Demo: const plain = 'Call me Ishmael.'; const encrypted = encrypt(plain); const decrypted = decrypt(encrypted); console.log(`Original: ${plain}`); console.log(`Encrypted: ${encrypted}`); console.log(`Decrypted: ${decrypted}`); //------------------------------------------ API: const EXPRESS = require('@runkit/runkit/express-endpoint/1.0.0'); const APP = EXPRESS(exports); const HELP = `<p>Available methods:</p> <ul> <li> <code>/encrypt</code> <br /> Params: <code>plain</code>, <code>secret</code> <br /> Example: <a href="${process.env.RUNKIT_ENDPOINT_URL}encrypt?plain=one%20two%20three&secret=zecretPassw0rd"><code>/encrypt?plain=one%20two%20three&secret=zecretPassw0rd</code></a> </li> <li> <code>/decrypt</code> <br /> Params: <code>encrypted</code>, <code>secret</code> <br /> Example: <a href="${process.env.RUNKIT_ENDPOINT_URL}decrypt?encrypted=be389e1cc854b20da37feb3ede&secret=zecretPassw0rd"><code>/decrypt?encrypted=be389e1cc854b20da37feb3ede&secret=zecretPassw0rd</code></a> </li> </ul>`; APP.get('/encrypt', (req, res) => { if (req.query && req.query.plain && req.query.secret) res.send(encrypt(req.query.plain, req.query.secret)); else res.status(400).send('<h1>Error!</h1>' + HELP); }); APP.get('/decrypt', (req, res) => { if (req.query && req.query.encrypted && req.query.secret) res.send(decrypt(req.query.encrypted, req.query.secret)); else res.status(400).send('<h1>Error!</h1>' + HELP); }); APP.get('*', (req, res) => res.status(400).send(HELP))
Loading…

no comments

    sign in to comment