You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

pem.js 1.2KB

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