crypto example

node v10.23.3
version: master
endpointsharetweet
//code from https://codeforgeek.com/encrypt-and-decrypt-data-in-node-js/ const crypto = require("crypto") const algorithm = "aes-256-cbc" //use the aes256 encryption algorithm const key = "pineapple whalespineapple whales"; //key has to be 32 chars long const iv = "pineapple whales"; //iv has to be 16 chars long /* const key = process.ENV.KEY const iv = process.ENV.IV if (key.length !== 32 || iv.length !==) { console.error("Key and IV lengths are invalid") } */ //key, iv are secrets and used to decrypt //more info: https://nodejs.org/en/knowledge/cryptography/how-to-use-crypto-module/ encrypt = (text) => { var cipher = crypto.createCipheriv('aes-256-cbc', Buffer.from(key), iv); //syntax: createCipheriv(algorithm, key, iv ( or initialization vector)) let encrypted = cipher.update(text); encrypted = Buffer.concat([encrypted, cipher.final()]); //cipher.final returns "Any remaining enciphered contents" //https://nodejs.org/api/crypto.html#crypto_cipher_final_outputencoding return encrypted; } decrypt = (text) => { var encryptedText = Buffer.from(text); var decipher = crypto.createDecipheriv('aes-256-cbc', Buffer.from(key), iv); //note the presence of iv var decrypted = decipher.update(encryptedText); decrypted = Buffer.concat([decrypted, decipher.final()]); return decrypted.toString("utf8"); //decrypted returns a buffer of hexadecimal values. Convert them to utf8 values. } var encryptedValue = encrypt("hello world") console.log(encryptedValue.toJSON()) console.log(encryptedValue.toString('base64')) console.log(encryptedValue.toString('utf8')) console.log(encryptedValue.toString("hex")) decrypt(encryptedValue.toString('utf8')) //var decryptedValue = decrypt(encryptedValue) console.log(Buffer.from()) /* var resultArr = encryptedValue .toJSON().data console.log(resultArr) console.log(decrypt(resultArr)) */
Loading…

no comments

    sign in to comment