auto.js 1.9 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273
  1. // Copyright 2015 Joyent, Inc.
  2. module.exports = {
  3. read: read,
  4. write: write
  5. };
  6. var assert = require('assert-plus');
  7. var utils = require('../utils');
  8. var Key = require('../key');
  9. var PrivateKey = require('../private-key');
  10. var pem = require('./pem');
  11. var ssh = require('./ssh');
  12. var rfc4253 = require('./rfc4253');
  13. function read(buf, options) {
  14. if (typeof (buf) === 'string') {
  15. if (buf.trim().match(/^[-]+[ ]*BEGIN/))
  16. return (pem.read(buf, options));
  17. if (buf.match(/^\s*ssh-[a-z]/))
  18. return (ssh.read(buf, options));
  19. if (buf.match(/^\s*ecdsa-/))
  20. return (ssh.read(buf, options));
  21. buf = new Buffer(buf, 'binary');
  22. } else {
  23. assert.buffer(buf);
  24. if (findPEMHeader(buf))
  25. return (pem.read(buf, options));
  26. if (findSSHHeader(buf))
  27. return (ssh.read(buf, options));
  28. }
  29. if (buf.readUInt32BE(0) < buf.length)
  30. return (rfc4253.read(buf, options));
  31. throw (new Error('Failed to auto-detect format of key'));
  32. }
  33. function findSSHHeader(buf) {
  34. var offset = 0;
  35. while (offset < buf.length &&
  36. (buf[offset] === 32 || buf[offset] === 10 || buf[offset] === 9))
  37. ++offset;
  38. if (offset + 4 <= buf.length &&
  39. buf.slice(offset, offset + 4).toString('ascii') === 'ssh-')
  40. return (true);
  41. if (offset + 6 <= buf.length &&
  42. buf.slice(offset, offset + 6).toString('ascii') === 'ecdsa-')
  43. return (true);
  44. return (false);
  45. }
  46. function findPEMHeader(buf) {
  47. var offset = 0;
  48. while (offset < buf.length &&
  49. (buf[offset] === 32 || buf[offset] === 10))
  50. ++offset;
  51. if (buf[offset] !== 45)
  52. return (false);
  53. while (offset < buf.length &&
  54. (buf[offset] === 45))
  55. ++offset;
  56. while (offset < buf.length &&
  57. (buf[offset] === 32))
  58. ++offset;
  59. if (offset + 5 > buf.length ||
  60. buf.slice(offset, offset + 5).toString('ascii') !== 'BEGIN')
  61. return (false);
  62. return (true);
  63. }
  64. function write(key, options) {
  65. throw (new Error('"auto" format cannot be used for writing'));
  66. }