Symmetric encryption with NodeJS

node v6.17.1
version: 2.0.0
endpointsharetweet
Use this either through the public endpoint for a quick encryption/decryption, eg. /e/value/key or /d/value/key Or set appropriate environment variables and run the first block to get encrypted value (https://runkit.com/settings/environment)
const crypto = require('crypto'); const key = process.env.ENCRYPTION_KEY || "secret"; const algorithm = process.env.ENCRYPTION_ALGORITHM || 'aes256'; const inputEncoding = process.env.ENCRYPTION_INPUT_ENCODING || 'utf8'; const outputEncoding = process.env.ENCRYPTION_OUTPUT_ENCODING || 'hex'; (function test(input) { const encrypted = encrypt(input) require('assert')(decrypt(encrypted) === input, 'FAILED') return encrypted }(process.env.ENCRYPTION_INPUT || 'test'))
function encrypt(value, useKey = key) { var cipher = crypto.createCipher(algorithm, key); var encrypted = cipher.update(value, inputEncoding, outputEncoding); encrypted += cipher.final(outputEncoding) return encrypted }
function decrypt(encrypted, useKey = key) { var decipher = crypto.createDecipher(algorithm, key); var decrypted = decipher.update(encrypted, outputEncoding, inputEncoding) decrypted += decipher.final(inputEncoding) return decrypted }
const url = require('url') exports.endpoint = function(request, response) { try { const {path} = url.parse(request.url) const [direction, value, key] = path.split('/').slice(5) if (direction === 'e' || direction === 'encrypt') { response.end(encrypt(value, key)) } else if (direction === 'd' || direction === 'decrypt') { response.end(decrypt(value, key)) } else { response.end('Use /<e|d>/<value>/[key] format of request') } } catch (err) { response.end('Unexpected error: ' + err) } }
Loading…

no comments

    sign in to comment