Book a Demo!
CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutPoliciesSign UpSign In
Download
80555 views
1
// adapted from https://github.com/apatil/pemstrip
2
var findProc = /Proc-Type: 4,ENCRYPTED\r?\nDEK-Info: AES-((?:128)|(?:192)|(?:256))-CBC,([0-9A-H]+)\r?\n\r?\n([0-9A-z\n\r\+\/\=]+)\r?\n/m;
3
var startRegex =/^-----BEGIN (.*) KEY-----\r?\n/m;
4
var fullRegex = /^-----BEGIN (.*) KEY-----\r?\n([0-9A-z\n\r\+\/\=]+)\r?\n-----END \1 KEY-----$/m;
5
var evp = require('./EVP_BytesToKey');
6
var ciphers = require('browserify-aes');
7
module.exports = function (okey, password) {
8
var key = okey.toString();
9
var match = key.match(findProc);
10
var decrypted;
11
if (!match) {
12
var match2 = key.match(fullRegex);
13
decrypted = new Buffer(match2[2].replace(/\r?\n/g, ''), 'base64');
14
} else {
15
var suite = 'aes' + match[1];
16
var iv = new Buffer(match[2], 'hex');
17
var cipherText = new Buffer(match[3].replace(/\r?\n/g, ''), 'base64');
18
var cipherKey = evp(password, iv.slice(0,8), parseInt(match[1]));
19
var out = [];
20
var cipher = ciphers.createDecipheriv(suite, cipherKey, iv);
21
out.push(cipher.update(cipherText));
22
out.push(cipher.final());
23
decrypted = Buffer.concat(out);
24
}
25
var tag = key.match(startRegex)[1] + ' KEY';
26
return {
27
tag: tag,
28
data: decrypted
29
};
30
};
31
32
// http://stackoverflow.com/a/7033705
33
function wrap (str) {
34
var chunks = []
35
36
for (var i = 0; i < str.length; i += 64) {
37
chunks.push(str.slice(i, i + 64))
38
}
39
return chunks.join("\n")
40
}
41
42