-
Notifications
You must be signed in to change notification settings - Fork 0
Open
Description
This just cleans up the API:
- makes it possible to have multiple instances
- removes the 'bespoke' prefix (no standards for encoding exist, AFAIK, so it's all 'bespoke')
- places IV before and after the data (the backup is small, and without the IV, the data is unrecoverable)
"use strict";
let Crypto = require("crypto");
let Cipher = module.exports;
const ALG = "aes-128-cbc";
const IV_SIZE = 16;
/**
* @param {Buffer} key128
*/
Cipher.create = function (key128) {
//let sharedSecret = Buffer.from(key128, "base64");
let cipher = {};
/**
* @param {String} plaintext
*/
cipher.encrypt = function (plaintext) {
let initializationVector = Crypto.randomBytes(IV_SIZE); // IV is always 16-bytes
let encrypted = "";
let _cipher = Crypto.createCipheriv(ALG, key128, initializationVector);
encrypted += _cipher.update(plaintext, "utf8", "base64");
encrypted += _cipher.final("base64");
let iv64 = toWeb64(initializationVector.toString("base64"));
let enc64 = toWeb64(encrypted);
// store iv64 twice, as a backup
return `${iv64}:${enc64}:${iv64}`;
};
/**
* @param {String} parts
*/
cipher.decrypt = function (parts) {
let [initializationVector, encrypted, initializationVectorBak] =
parts.split(":");
let plaintext = "";
if (initializationVector !== initializationVectorBak) {
console.error("corrupt (but possibly recoverable) initialization vector");
}
let iv = Buffer.from(initializationVector, "base64");
let _cipher = Crypto.createDecipheriv(ALG, key128, iv);
plaintext += _cipher.update(encrypted, "base64", "utf8");
plaintext += _cipher.final("utf8");
return plaintext;
};
return cipher;
};
/**
* @param {String} x
*/
function toWeb64(x) {
return x.replace(/\+/g, "-").replace(/\//g, "_").replace(/=/g, "");
}Reactions are currently unavailable
Metadata
Metadata
Assignees
Labels
No labels