-
-
Save zachowj/193c1d7ee53833a1e18358597e589106 to your computer and use it in GitHub Desktop.
reencrypt <old key> <flows_cred.js> <new key> <flow_cred_new.js>
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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