Browse Source

add PEM parser / packer

tags/v1.0.0
AJ ONeal 10 months ago
parent
commit
6b3f1cb6a1
2 changed files with 34 additions and 0 deletions
  1. 13
    0
      lib/pem-packer.js
  2. 21
    0
      lib/pem-parser.js

+ 13
- 0
lib/pem-packer.js View File

@@ -0,0 +1,13 @@
1
+'use strict';
2
+
3
+var PEM = module.exports;
4
+var Enc = require('./encoding.js');
5
+
6
+PEM.packBlock = function (opts) {
7
+  var n = opts.lineLength || 64;
8
+  var re = new RegExp('.{1,' + n + '}', 'g');
9
+  return '-----BEGIN ' + opts.type + '-----\n'
10
+    + Enc.bufToBase64(opts.bytes).match(re).join('\n') + '\n'
11
+    + '-----END ' + opts.type + '-----'
12
+  ;
13
+};

+ 21
- 0
lib/pem-parser.js View File

@@ -0,0 +1,21 @@
1
+'use strict';
2
+
3
+var PEM = module.exports;
4
+var Enc = require('./encoding.js');
5
+
6
+PEM.parseBlock = function pemToDer(pem) {
7
+  var lines = pem.trim().split(/\n/);
8
+  var end = lines.length - 1;
9
+  var head = lines[0].match(/-----BEGIN (.*)-----/);
10
+  var foot = lines[end].match(/-----END (.*)-----/);
11
+
12
+  if (head) {
13
+    lines = lines.slice(1, end);
14
+    head = head[1];
15
+    if (head !== foot[1]) {
16
+      throw new Error("headers and footers do not match");
17
+    }
18
+  }
19
+
20
+  return { type: head, bytes: Enc.base64ToBuf(lines.join('')) };
21
+};

Loading…
Cancel
Save