private-key.js 6.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252
  1. // Copyright 2017 Joyent, Inc.
  2. module.exports = PrivateKey;
  3. var assert = require('assert-plus');
  4. var algs = require('./algs');
  5. var crypto = require('crypto');
  6. var Fingerprint = require('./fingerprint');
  7. var Signature = require('./signature');
  8. var errs = require('./errors');
  9. var util = require('util');
  10. var utils = require('./utils');
  11. var dhe = require('./dhe');
  12. var generateECDSA = dhe.generateECDSA;
  13. var generateED25519 = dhe.generateED25519;
  14. var edCompat;
  15. var nacl;
  16. try {
  17. edCompat = require('./ed-compat');
  18. } catch (e) {
  19. /* Just continue through, and bail out if we try to use it. */
  20. }
  21. var Key = require('./key');
  22. var InvalidAlgorithmError = errs.InvalidAlgorithmError;
  23. var KeyParseError = errs.KeyParseError;
  24. var KeyEncryptedError = errs.KeyEncryptedError;
  25. var formats = {};
  26. formats['auto'] = require('./formats/auto');
  27. formats['pem'] = require('./formats/pem');
  28. formats['pkcs1'] = require('./formats/pkcs1');
  29. formats['pkcs8'] = require('./formats/pkcs8');
  30. formats['rfc4253'] = require('./formats/rfc4253');
  31. formats['ssh-private'] = require('./formats/ssh-private');
  32. formats['openssh'] = formats['ssh-private'];
  33. formats['ssh'] = formats['ssh-private'];
  34. formats['dnssec'] = require('./formats/dnssec');
  35. function PrivateKey(opts) {
  36. assert.object(opts, 'options');
  37. Key.call(this, opts);
  38. this._pubCache = undefined;
  39. }
  40. util.inherits(PrivateKey, Key);
  41. PrivateKey.formats = formats;
  42. PrivateKey.prototype.toBuffer = function (format, options) {
  43. if (format === undefined)
  44. format = 'pkcs1';
  45. assert.string(format, 'format');
  46. assert.object(formats[format], 'formats[format]');
  47. assert.optionalObject(options, 'options');
  48. return (formats[format].write(this, options));
  49. };
  50. PrivateKey.prototype.hash = function (algo) {
  51. return (this.toPublic().hash(algo));
  52. };
  53. PrivateKey.prototype.toPublic = function () {
  54. if (this._pubCache)
  55. return (this._pubCache);
  56. var algInfo = algs.info[this.type];
  57. var pubParts = [];
  58. for (var i = 0; i < algInfo.parts.length; ++i) {
  59. var p = algInfo.parts[i];
  60. pubParts.push(this.part[p]);
  61. }
  62. this._pubCache = new Key({
  63. type: this.type,
  64. source: this,
  65. parts: pubParts
  66. });
  67. if (this.comment)
  68. this._pubCache.comment = this.comment;
  69. return (this._pubCache);
  70. };
  71. PrivateKey.prototype.derive = function (newType) {
  72. assert.string(newType, 'type');
  73. var priv, pub, pair;
  74. if (this.type === 'ed25519' && newType === 'curve25519') {
  75. if (nacl === undefined)
  76. nacl = require('tweetnacl');
  77. priv = this.part.k.data;
  78. if (priv[0] === 0x00)
  79. priv = priv.slice(1);
  80. pair = nacl.box.keyPair.fromSecretKey(new Uint8Array(priv));
  81. pub = new Buffer(pair.publicKey);
  82. return (new PrivateKey({
  83. type: 'curve25519',
  84. parts: [
  85. { name: 'A', data: utils.mpNormalize(pub) },
  86. { name: 'k', data: utils.mpNormalize(priv) }
  87. ]
  88. }));
  89. } else if (this.type === 'curve25519' && newType === 'ed25519') {
  90. if (nacl === undefined)
  91. nacl = require('tweetnacl');
  92. priv = this.part.k.data;
  93. if (priv[0] === 0x00)
  94. priv = priv.slice(1);
  95. pair = nacl.sign.keyPair.fromSeed(new Uint8Array(priv));
  96. pub = new Buffer(pair.publicKey);
  97. return (new PrivateKey({
  98. type: 'ed25519',
  99. parts: [
  100. { name: 'A', data: utils.mpNormalize(pub) },
  101. { name: 'k', data: utils.mpNormalize(priv) }
  102. ]
  103. }));
  104. }
  105. throw (new Error('Key derivation not supported from ' + this.type +
  106. ' to ' + newType));
  107. };
  108. PrivateKey.prototype.createVerify = function (hashAlgo) {
  109. return (this.toPublic().createVerify(hashAlgo));
  110. };
  111. PrivateKey.prototype.createSign = function (hashAlgo) {
  112. if (hashAlgo === undefined)
  113. hashAlgo = this.defaultHashAlgorithm();
  114. assert.string(hashAlgo, 'hash algorithm');
  115. /* ED25519 is not supported by OpenSSL, use a javascript impl. */
  116. if (this.type === 'ed25519' && edCompat !== undefined)
  117. return (new edCompat.Signer(this, hashAlgo));
  118. if (this.type === 'curve25519')
  119. throw (new Error('Curve25519 keys are not suitable for ' +
  120. 'signing or verification'));
  121. var v, nm, err;
  122. try {
  123. nm = hashAlgo.toUpperCase();
  124. v = crypto.createSign(nm);
  125. } catch (e) {
  126. err = e;
  127. }
  128. if (v === undefined || (err instanceof Error &&
  129. err.message.match(/Unknown message digest/))) {
  130. nm = 'RSA-';
  131. nm += hashAlgo.toUpperCase();
  132. v = crypto.createSign(nm);
  133. }
  134. assert.ok(v, 'failed to create verifier');
  135. var oldSign = v.sign.bind(v);
  136. var key = this.toBuffer('pkcs1');
  137. var type = this.type;
  138. var curve = this.curve;
  139. v.sign = function () {
  140. var sig = oldSign(key);
  141. if (typeof (sig) === 'string')
  142. sig = new Buffer(sig, 'binary');
  143. sig = Signature.parse(sig, type, 'asn1');
  144. sig.hashAlgorithm = hashAlgo;
  145. sig.curve = curve;
  146. return (sig);
  147. };
  148. return (v);
  149. };
  150. PrivateKey.parse = function (data, format, options) {
  151. if (typeof (data) !== 'string')
  152. assert.buffer(data, 'data');
  153. if (format === undefined)
  154. format = 'auto';
  155. assert.string(format, 'format');
  156. if (typeof (options) === 'string')
  157. options = { filename: options };
  158. assert.optionalObject(options, 'options');
  159. if (options === undefined)
  160. options = {};
  161. assert.optionalString(options.filename, 'options.filename');
  162. if (options.filename === undefined)
  163. options.filename = '(unnamed)';
  164. assert.object(formats[format], 'formats[format]');
  165. try {
  166. var k = formats[format].read(data, options);
  167. assert.ok(k instanceof PrivateKey, 'key is not a private key');
  168. if (!k.comment)
  169. k.comment = options.filename;
  170. return (k);
  171. } catch (e) {
  172. if (e.name === 'KeyEncryptedError')
  173. throw (e);
  174. throw (new KeyParseError(options.filename, format, e));
  175. }
  176. };
  177. PrivateKey.isPrivateKey = function (obj, ver) {
  178. return (utils.isCompatible(obj, PrivateKey, ver));
  179. };
  180. PrivateKey.generate = function (type, options) {
  181. if (options === undefined)
  182. options = {};
  183. assert.object(options, 'options');
  184. switch (type) {
  185. case 'ecdsa':
  186. if (options.curve === undefined)
  187. options.curve = 'nistp256';
  188. assert.string(options.curve, 'options.curve');
  189. return (generateECDSA(options.curve));
  190. case 'ed25519':
  191. return (generateED25519());
  192. default:
  193. throw (new Error('Key generation not supported with key ' +
  194. 'type "' + type + '"'));
  195. }
  196. };
  197. /*
  198. * API versions for PrivateKey:
  199. * [1,0] -- initial ver
  200. * [1,1] -- added auto, pkcs[18], openssh/ssh-private formats
  201. * [1,2] -- added defaultHashAlgorithm
  202. * [1,3] -- added derive, ed, createDH
  203. * [1,4] -- first tagged version
  204. * [1,5] -- changed ed25519 part names and format
  205. */
  206. PrivateKey.prototype._sshpkApiVersion = [1, 5];
  207. PrivateKey._oldVersionDetect = function (obj) {
  208. assert.func(obj.toPublic);
  209. assert.func(obj.createSign);
  210. if (obj.derive)
  211. return ([1, 3]);
  212. if (obj.defaultHashAlgorithm)
  213. return ([1, 2]);
  214. if (obj.formats['auto'])
  215. return ([1, 1]);
  216. return ([1, 0]);
  217. };