pem.js 1.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051
  1. 'use strict';
  2. const inherits = require('inherits');
  3. const Buffer = require('safer-buffer').Buffer;
  4. const DERDecoder = require('./der');
  5. function PEMDecoder(entity) {
  6. DERDecoder.call(this, entity);
  7. this.enc = 'pem';
  8. }
  9. inherits(PEMDecoder, DERDecoder);
  10. module.exports = PEMDecoder;
  11. PEMDecoder.prototype.decode = function decode(data, options) {
  12. const lines = data.toString().split(/[\r\n]+/g);
  13. const label = options.label.toUpperCase();
  14. const re = /^-----(BEGIN|END) ([^-]+)-----$/;
  15. let start = -1;
  16. let end = -1;
  17. for (let i = 0; i < lines.length; i++) {
  18. const match = lines[i].match(re);
  19. if (match === null)
  20. continue;
  21. if (match[2] !== label)
  22. continue;
  23. if (start === -1) {
  24. if (match[1] !== 'BEGIN')
  25. break;
  26. start = i;
  27. } else {
  28. if (match[1] !== 'END')
  29. break;
  30. end = i;
  31. break;
  32. }
  33. }
  34. if (start === -1 || end === -1)
  35. throw new Error('PEM section not found for: ' + label);
  36. const base64 = lines.slice(start + 1, end).join('');
  37. // Remove excessive symbols
  38. base64.replace(/[^a-z0-9+/=]+/gi, '');
  39. const input = Buffer.from(base64, 'base64');
  40. return DERDecoder.prototype.decode.call(this, input, options);
  41. };