Skip to content

Instantly share code, notes, and snippets.

@adeonhy
Created Sep 23, 2020
Embed
What would you like to do?
うまく動かなかったやつ
const fs = require('fs')
const crypto = require('crypto')
const readline = require('readline');
const ALGORITHM = 'aes-256-cbc';
// main
// node crypter.js [enc/dec] [in filename] [out filename]
(async () => {
const args = process.argv.slice(2);
if (args.length !== 3) { usage() }
const [subCmd, inFile, outFile] = args;
let data, key
switch (subCmd) {
case 'enc':
data = fs.readFileSync(inFile);
key = await getKey('Password: ');
const encData = encryptBase64(data, key);
fs.writeFileSync(outFile, encData);
break;
case 'dec':
data = fs.readFileSync(inFile);
key = await getKey('Password: ');
console.log(key)
const decData = decryptBase64(data, key);
fs.writeFileSync(outFile, decData)
break;
default:
usage();
break;
}
})();
function usage() {
console.log('node crypter.js [enc/dec] [in filename] [out filename]');
process.exit(1);
}
function encryptBase64(data, keyStr) {
const key = Buffer.from(keyStr);
const iv = crypto.randomBytes(16);
const cipher = crypto.createCipheriv(ALGORITHM, key, iv);
const encData = cipher.update(Buffer.from(data));
return Buffer.concat([iv, encData, cipher.final()]).toString('base64');
}
function decryptBase64(data, keyStr) {
const key = Buffer.from(keyStr);
const buff = Buffer.from(data, 'base64');
const iv = buff.slice(0, 16);
const encData = buff.slice(16);
const decipher = crypto.createDecipheriv(ALGORITHM, key, iv);
const decData = decipher.update(encData);
return Buffer.concat([decData, decipher.final()]).toString('utf8');
}
async function getKey(prompt) {
const key = await getPassword(prompt);
if (key.length !== 32) {
console.error('key length must be 32');
process.exit(1);
}
return key
}
function getPassword(prompt) {
return new Promise(resolve => {
const rl = readline.createInterface({
input: process.stdin,
output: process.stderr,
});
rl.stdoutMuted = true;
rl.query = prompt;
rl.question(rl.query, function (password) {
resolve(password);
rl.close();
});
rl._writeToOutput = function _writeToOutput(stringToWrite) {
if (rl.stdoutMuted)
rl.output.write("*");
else
rl.output.write(stringToWrite);
};
})
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment