Skip to content

Instantly share code, notes, and snippets.

@zachowj
Last active March 6, 2021 00:52
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save zachowj/193c1d7ee53833a1e18358597e589106 to your computer and use it in GitHub Desktop.
Save zachowj/193c1d7ee53833a1e18358597e589106 to your computer and use it in GitHub Desktop.
reencrypt <old key> <flows_cred.js> <new key> <flow_cred_new.js>
const crypto = require("crypto");
const fs = require("fs");
const { exit } = require("process");
const encryptionAlgorithm = "aes-256-ctr";
function processFiles() {
const args = process.argv.slice(2);
if (args.length !== 4) {
console.error(
"reencrypt <old key> <flows_cred.js> <new key> <flow_cred_new.js>"
);
exit(1);
}
const [key, oldCredsFile, newKey, newCredsFile] = args;
const encryptionKey = crypto.createHash("sha256").update(key).digest();
let decryptedCreds;
try {
const data = fs.readFileSync(oldCredsFile, "utf8");
decryptedCreds = decryptCredentials(encryptionKey, JSON.parse(data));
} catch (err) {
console.error(err);
}
const newEncryptionKey = crypto.createHash("sha256").update(newKey).digest();
console.log("decryptedCreds :>> ", decryptedCreds);
const content = encryptCredentials(newEncryptionKey, decryptedCreds);
try {
fs.writeFileSync(newCredsFile, JSON.stringify(content, null, 4));
console.log(`new creds written to ${newCredsFile} with key '${newKey}'`);
} catch (err) {
console.error(err);
}
}
function decryptCredentials(key, credentials) {
let creds = credentials["$"];
const initVector = Buffer.from(creds.substring(0, 32), "hex");
creds = creds.substring(32);
const decipher = crypto.createDecipheriv(
encryptionAlgorithm,
key,
initVector
);
const decrypted =
decipher.update(creds, "base64", "utf8") + decipher.final("utf8");
return JSON.parse(decrypted);
}
function encryptCredentials(key, credentials) {
const initVector = crypto.randomBytes(16);
const cipher = crypto.createCipheriv(encryptionAlgorithm, key, initVector);
return {
$:
initVector.toString("hex") +
cipher.update(JSON.stringify(credentials), "utf8", "base64") +
cipher.final("base64"),
};
}
processFiles();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment