private-key.js 6.6 KB

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