x509-pem.js 1.8 KB

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