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