1
|
var inherits = require('inherits');
|
2
|
var Buffer = require('buffer').Buffer;
|
3
|
|
4
|
var DERDecoder = require('./der');
|
5
|
|
6
|
function PEMDecoder(entity) {
|
7
|
DERDecoder.call(this, entity);
|
8
|
this.enc = 'pem';
|
9
|
};
|
10
|
inherits(PEMDecoder, DERDecoder);
|
11
|
module.exports = PEMDecoder;
|
12
|
|
13
|
PEMDecoder.prototype.decode = function decode(data, options) {
|
14
|
var lines = data.toString().split(/[\r\n]+/g);
|
15
|
|
16
|
var label = options.label.toUpperCase();
|
17
|
|
18
|
var re = /^-----(BEGIN|END) ([^-]+)-----$/;
|
19
|
var start = -1;
|
20
|
var end = -1;
|
21
|
for (var i = 0; i < lines.length; i++) {
|
22
|
var match = lines[i].match(re);
|
23
|
if (match === null)
|
24
|
continue;
|
25
|
|
26
|
if (match[2] !== label)
|
27
|
continue;
|
28
|
|
29
|
if (start === -1) {
|
30
|
if (match[1] !== 'BEGIN')
|
31
|
break;
|
32
|
start = i;
|
33
|
} else {
|
34
|
if (match[1] !== 'END')
|
35
|
break;
|
36
|
end = i;
|
37
|
break;
|
38
|
}
|
39
|
}
|
40
|
if (start === -1 || end === -1)
|
41
|
throw new Error('PEM section not found for: ' + label);
|
42
|
|
43
|
var base64 = lines.slice(start + 1, end).join('');
|
44
|
// Remove excessive symbols
|
45
|
base64.replace(/[^a-z0-9\+\/=]+/gi, '');
|
46
|
|
47
|
var input = new Buffer(base64, 'base64');
|
48
|
return DERDecoder.prototype.decode.call(this, input, options);
|
49
|
};
|