x509-pem.js
2 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
// Copyright 2016 Joyent, Inc.
var x509 = require('./x509');
module.exports = {
read: read,
verify: x509.verify,
sign: x509.sign,
write: write
};
var assert = require('assert-plus');
var asn1 = require('asn1');
var Buffer = require('safer-buffer').Buffer;
var algs = require('../algs');
var utils = require('../utils');
var Key = require('../key');
var PrivateKey = require('../private-key');
var pem = require('./pem');
var Identity = require('../identity');
var Signature = require('../signature');
var Certificate = require('../certificate');
function read(buf, options) {
if (typeof (buf) !== 'string') {
assert.buffer(buf, 'buf');
buf = buf.toString('ascii');
}
var lines = buf.trim().split(/[\r\n]+/g);
var m;
var si = -1;
while (!m && si < lines.length) {
m = lines[++si].match(/*JSSTYLED*/
/[-]+[ ]*BEGIN CERTIFICATE[ ]*[-]+/);
}
assert.ok(m, 'invalid PEM header');
var m2;
var ei = lines.length;
while (!m2 && ei > 0) {
m2 = lines[--ei].match(/*JSSTYLED*/
/[-]+[ ]*END CERTIFICATE[ ]*[-]+/);
}
assert.ok(m2, 'invalid PEM footer');
lines = lines.slice(si, ei + 1);
var headers = {};
while (true) {
lines = lines.slice(1);
m = lines[0].match(/*JSSTYLED*/
/^([A-Za-z0-9-]+): (.+)$/);
if (!m)
break;
headers[m[1].toLowerCase()] = m[2];
}
/* Chop off the first and last lines */
lines = lines.slice(0, -1).join('');
buf = Buffer.from(lines, 'base64');
return (x509.read(buf, options));
}
function write(cert, options) {
var dbuf = x509.write(cert, options);
var header = 'CERTIFICATE';
var tmp = dbuf.toString('base64');
var len = tmp.length + (tmp.length / 64) +
18 + 16 + header.length*2 + 10;
var buf = Buffer.alloc(len);
var o = 0;
o += buf.write('-----BEGIN ' + header + '-----\n', o);
for (var i = 0; i < tmp.length; ) {
var limit = i + 64;
if (limit > tmp.length)
limit = tmp.length;
o += buf.write(tmp.slice(i, limit), o);
buf[o++] = 10;
i = limit;
}
o += buf.write('-----END ' + header + '-----\n', o);
return (buf.slice(0, o));
}