private-key.js 6.4 KB

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