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