private-key.js 6.6 KB

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