var findProc = /Proc-Type: 4,ENCRYPTED\n\r?DEK-Info: AES-((?:128)|(?:192)|(?:256))-CBC,([0-9A-H]+)\n\r?\n\r?([0-9A-z\n\r\+\/\=]+)\n\r?/m;
var startRegex = /^-----BEGIN (.*)-----\n/;
var evp = require('./EVP_BytesToKey');
module.exports = function (okey, password, crypto) {
var key = okey.toString();
var match = key.match(findProc);
if (!match) {
return okey;
}
var suite = 'aes' + match[1];
var iv = new Buffer(match[2], 'hex');
var cipherText = new Buffer(match[3].replace(/\n\r?/g, ''), 'base64');
var cipherKey = evp(crypto, password, iv.slice(0,8), parseInt(match[1]));
var out = [];
var cipher = crypto.createDecipheriv(suite, cipherKey, iv);
out.push(cipher.update(cipherText));
out.push(cipher.final());
var decrypted = Buffer.concat(out).toString('base64');
var tag = key.match(startRegex)[1];
return '-----BEGIN ' + tag + "-----\n" + wrap(decrypted) + "\n" + '-----END ' + tag + "-----\n";
};
// http://stackoverflow.com/a/7033705
function wrap(str) {
var chunks = [];
while (str) {
if (str.length < 64) {
chunks.push(str);
break;
}
else {
chunks.push(str.slice(0, 64));
str = str.slice(64);
}
}
return chunks.join("\n");
} |