pkcs8.js 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643
  1. // Copyright 2018 Joyent, Inc.
  2. module.exports = {
  3. read: read,
  4. readPkcs8: readPkcs8,
  5. write: write,
  6. writePkcs8: writePkcs8,
  7. pkcs8ToBuffer: pkcs8ToBuffer,
  8. readECDSACurve: readECDSACurve,
  9. writeECDSACurve: writeECDSACurve
  10. };
  11. var assert = require('assert-plus');
  12. var asn1 = require('asn1');
  13. var Buffer = require('safer-buffer').Buffer;
  14. var algs = require('../algs');
  15. var utils = require('../utils');
  16. var Key = require('../key');
  17. var PrivateKey = require('../private-key');
  18. var pem = require('./pem');
  19. function read(buf, options) {
  20. return (pem.read(buf, options, 'pkcs8'));
  21. }
  22. function write(key, options) {
  23. return (pem.write(key, options, 'pkcs8'));
  24. }
  25. /* Helper to read in a single mpint */
  26. function readMPInt(der, nm) {
  27. assert.strictEqual(der.peek(), asn1.Ber.Integer,
  28. nm + ' is not an Integer');
  29. return (utils.mpNormalize(der.readString(asn1.Ber.Integer, true)));
  30. }
  31. function readPkcs8(alg, type, der) {
  32. /* Private keys in pkcs#8 format have a weird extra int */
  33. if (der.peek() === asn1.Ber.Integer) {
  34. assert.strictEqual(type, 'private',
  35. 'unexpected Integer at start of public key');
  36. der.readString(asn1.Ber.Integer, true);
  37. }
  38. der.readSequence();
  39. var next = der.offset + der.length;
  40. var oid = der.readOID();
  41. switch (oid) {
  42. case '1.2.840.113549.1.1.1':
  43. der._offset = next;
  44. if (type === 'public')
  45. return (readPkcs8RSAPublic(der));
  46. else
  47. return (readPkcs8RSAPrivate(der));
  48. case '1.2.840.10040.4.1':
  49. if (type === 'public')
  50. return (readPkcs8DSAPublic(der));
  51. else
  52. return (readPkcs8DSAPrivate(der));
  53. case '1.2.840.10045.2.1':
  54. if (type === 'public')
  55. return (readPkcs8ECDSAPublic(der));
  56. else
  57. return (readPkcs8ECDSAPrivate(der));
  58. case '1.3.101.112':
  59. if (type === 'public') {
  60. return (readPkcs8EdDSAPublic(der));
  61. } else {
  62. return (readPkcs8EdDSAPrivate(der));
  63. }
  64. case '1.3.101.110':
  65. if (type === 'public') {
  66. return (readPkcs8X25519Public(der));
  67. } else {
  68. return (readPkcs8X25519Private(der));
  69. }
  70. default:
  71. throw (new Error('Unknown key type OID ' + oid));
  72. }
  73. }
  74. function readPkcs8RSAPublic(der) {
  75. // bit string sequence
  76. der.readSequence(asn1.Ber.BitString);
  77. der.readByte();
  78. der.readSequence();
  79. // modulus
  80. var n = readMPInt(der, 'modulus');
  81. var e = readMPInt(der, 'exponent');
  82. // now, make the key
  83. var key = {
  84. type: 'rsa',
  85. source: der.originalInput,
  86. parts: [
  87. { name: 'e', data: e },
  88. { name: 'n', data: n }
  89. ]
  90. };
  91. return (new Key(key));
  92. }
  93. function readPkcs8RSAPrivate(der) {
  94. der.readSequence(asn1.Ber.OctetString);
  95. der.readSequence();
  96. var ver = readMPInt(der, 'version');
  97. assert.equal(ver[0], 0x0, 'unknown RSA private key version');
  98. // modulus then public exponent
  99. var n = readMPInt(der, 'modulus');
  100. var e = readMPInt(der, 'public exponent');
  101. var d = readMPInt(der, 'private exponent');
  102. var p = readMPInt(der, 'prime1');
  103. var q = readMPInt(der, 'prime2');
  104. var dmodp = readMPInt(der, 'exponent1');
  105. var dmodq = readMPInt(der, 'exponent2');
  106. var iqmp = readMPInt(der, 'iqmp');
  107. // now, make the key
  108. var key = {
  109. type: 'rsa',
  110. parts: [
  111. { name: 'n', data: n },
  112. { name: 'e', data: e },
  113. { name: 'd', data: d },
  114. { name: 'iqmp', data: iqmp },
  115. { name: 'p', data: p },
  116. { name: 'q', data: q },
  117. { name: 'dmodp', data: dmodp },
  118. { name: 'dmodq', data: dmodq }
  119. ]
  120. };
  121. return (new PrivateKey(key));
  122. }
  123. function readPkcs8DSAPublic(der) {
  124. der.readSequence();
  125. var p = readMPInt(der, 'p');
  126. var q = readMPInt(der, 'q');
  127. var g = readMPInt(der, 'g');
  128. // bit string sequence
  129. der.readSequence(asn1.Ber.BitString);
  130. der.readByte();
  131. var y = readMPInt(der, 'y');
  132. // now, make the key
  133. var key = {
  134. type: 'dsa',
  135. parts: [
  136. { name: 'p', data: p },
  137. { name: 'q', data: q },
  138. { name: 'g', data: g },
  139. { name: 'y', data: y }
  140. ]
  141. };
  142. return (new Key(key));
  143. }
  144. function readPkcs8DSAPrivate(der) {
  145. der.readSequence();
  146. var p = readMPInt(der, 'p');
  147. var q = readMPInt(der, 'q');
  148. var g = readMPInt(der, 'g');
  149. der.readSequence(asn1.Ber.OctetString);
  150. var x = readMPInt(der, 'x');
  151. /* The pkcs#8 format does not include the public key */
  152. var y = utils.calculateDSAPublic(g, p, x);
  153. var key = {
  154. type: 'dsa',
  155. parts: [
  156. { name: 'p', data: p },
  157. { name: 'q', data: q },
  158. { name: 'g', data: g },
  159. { name: 'y', data: y },
  160. { name: 'x', data: x }
  161. ]
  162. };
  163. return (new PrivateKey(key));
  164. }
  165. function readECDSACurve(der) {
  166. var curveName, curveNames;
  167. var j, c, cd;
  168. if (der.peek() === asn1.Ber.OID) {
  169. var oid = der.readOID();
  170. curveNames = Object.keys(algs.curves);
  171. for (j = 0; j < curveNames.length; ++j) {
  172. c = curveNames[j];
  173. cd = algs.curves[c];
  174. if (cd.pkcs8oid === oid) {
  175. curveName = c;
  176. break;
  177. }
  178. }
  179. } else {
  180. // ECParameters sequence
  181. der.readSequence();
  182. var version = der.readString(asn1.Ber.Integer, true);
  183. assert.strictEqual(version[0], 1, 'ECDSA key not version 1');
  184. var curve = {};
  185. // FieldID sequence
  186. der.readSequence();
  187. var fieldTypeOid = der.readOID();
  188. assert.strictEqual(fieldTypeOid, '1.2.840.10045.1.1',
  189. 'ECDSA key is not from a prime-field');
  190. var p = curve.p = utils.mpNormalize(
  191. der.readString(asn1.Ber.Integer, true));
  192. /*
  193. * p always starts with a 1 bit, so count the zeros to get its
  194. * real size.
  195. */
  196. curve.size = p.length * 8 - utils.countZeros(p);
  197. // Curve sequence
  198. der.readSequence();
  199. curve.a = utils.mpNormalize(
  200. der.readString(asn1.Ber.OctetString, true));
  201. curve.b = utils.mpNormalize(
  202. der.readString(asn1.Ber.OctetString, true));
  203. if (der.peek() === asn1.Ber.BitString)
  204. curve.s = der.readString(asn1.Ber.BitString, true);
  205. // Combined Gx and Gy
  206. curve.G = der.readString(asn1.Ber.OctetString, true);
  207. assert.strictEqual(curve.G[0], 0x4,
  208. 'uncompressed G is required');
  209. curve.n = utils.mpNormalize(
  210. der.readString(asn1.Ber.Integer, true));
  211. curve.h = utils.mpNormalize(
  212. der.readString(asn1.Ber.Integer, true));
  213. assert.strictEqual(curve.h[0], 0x1, 'a cofactor=1 curve is ' +
  214. 'required');
  215. curveNames = Object.keys(algs.curves);
  216. var ks = Object.keys(curve);
  217. for (j = 0; j < curveNames.length; ++j) {
  218. c = curveNames[j];
  219. cd = algs.curves[c];
  220. var equal = true;
  221. for (var i = 0; i < ks.length; ++i) {
  222. var k = ks[i];
  223. if (cd[k] === undefined)
  224. continue;
  225. if (typeof (cd[k]) === 'object' &&
  226. cd[k].equals !== undefined) {
  227. if (!cd[k].equals(curve[k])) {
  228. equal = false;
  229. break;
  230. }
  231. } else if (Buffer.isBuffer(cd[k])) {
  232. if (cd[k].toString('binary')
  233. !== curve[k].toString('binary')) {
  234. equal = false;
  235. break;
  236. }
  237. } else {
  238. if (cd[k] !== curve[k]) {
  239. equal = false;
  240. break;
  241. }
  242. }
  243. }
  244. if (equal) {
  245. curveName = c;
  246. break;
  247. }
  248. }
  249. }
  250. return (curveName);
  251. }
  252. function readPkcs8ECDSAPrivate(der) {
  253. var curveName = readECDSACurve(der);
  254. assert.string(curveName, 'a known elliptic curve');
  255. der.readSequence(asn1.Ber.OctetString);
  256. der.readSequence();
  257. var version = readMPInt(der, 'version');
  258. assert.equal(version[0], 1, 'unknown version of ECDSA key');
  259. var d = der.readString(asn1.Ber.OctetString, true);
  260. var Q;
  261. if (der.peek() == 0xa0) {
  262. der.readSequence(0xa0);
  263. der._offset += der.length;
  264. }
  265. if (der.peek() == 0xa1) {
  266. der.readSequence(0xa1);
  267. Q = der.readString(asn1.Ber.BitString, true);
  268. Q = utils.ecNormalize(Q);
  269. }
  270. if (Q === undefined) {
  271. var pub = utils.publicFromPrivateECDSA(curveName, d);
  272. Q = pub.part.Q.data;
  273. }
  274. var key = {
  275. type: 'ecdsa',
  276. parts: [
  277. { name: 'curve', data: Buffer.from(curveName) },
  278. { name: 'Q', data: Q },
  279. { name: 'd', data: d }
  280. ]
  281. };
  282. return (new PrivateKey(key));
  283. }
  284. function readPkcs8ECDSAPublic(der) {
  285. var curveName = readECDSACurve(der);
  286. assert.string(curveName, 'a known elliptic curve');
  287. var Q = der.readString(asn1.Ber.BitString, true);
  288. Q = utils.ecNormalize(Q);
  289. var key = {
  290. type: 'ecdsa',
  291. parts: [
  292. { name: 'curve', data: Buffer.from(curveName) },
  293. { name: 'Q', data: Q }
  294. ]
  295. };
  296. return (new Key(key));
  297. }
  298. function readPkcs8EdDSAPublic(der) {
  299. if (der.peek() === 0x00)
  300. der.readByte();
  301. var A = utils.readBitString(der);
  302. var key = {
  303. type: 'ed25519',
  304. parts: [
  305. { name: 'A', data: utils.zeroPadToLength(A, 32) }
  306. ]
  307. };
  308. return (new Key(key));
  309. }
  310. function readPkcs8X25519Public(der) {
  311. var A = utils.readBitString(der);
  312. var key = {
  313. type: 'curve25519',
  314. parts: [
  315. { name: 'A', data: utils.zeroPadToLength(A, 32) }
  316. ]
  317. };
  318. return (new Key(key));
  319. }
  320. function readPkcs8EdDSAPrivate(der) {
  321. if (der.peek() === 0x00)
  322. der.readByte();
  323. der.readSequence(asn1.Ber.OctetString);
  324. var k = der.readString(asn1.Ber.OctetString, true);
  325. k = utils.zeroPadToLength(k, 32);
  326. var A, tag;
  327. while ((tag = der.peek()) !== null) {
  328. if (tag === (asn1.Ber.Context | 1)) {
  329. A = utils.readBitString(der, tag);
  330. } else {
  331. der.readSequence(tag);
  332. der._offset += der.length;
  333. }
  334. }
  335. if (A === undefined)
  336. A = utils.calculateED25519Public(k);
  337. var key = {
  338. type: 'ed25519',
  339. parts: [
  340. { name: 'A', data: utils.zeroPadToLength(A, 32) },
  341. { name: 'k', data: utils.zeroPadToLength(k, 32) }
  342. ]
  343. };
  344. return (new PrivateKey(key));
  345. }
  346. function readPkcs8X25519Private(der) {
  347. if (der.peek() === 0x00)
  348. der.readByte();
  349. der.readSequence(asn1.Ber.OctetString);
  350. var k = der.readString(asn1.Ber.OctetString, true);
  351. k = utils.zeroPadToLength(k, 32);
  352. var A = utils.calculateX25519Public(k);
  353. var key = {
  354. type: 'curve25519',
  355. parts: [
  356. { name: 'A', data: utils.zeroPadToLength(A, 32) },
  357. { name: 'k', data: utils.zeroPadToLength(k, 32) }
  358. ]
  359. };
  360. return (new PrivateKey(key));
  361. }
  362. function pkcs8ToBuffer(key) {
  363. var der = new asn1.BerWriter();
  364. writePkcs8(der, key);
  365. return (der.buffer);
  366. }
  367. function writePkcs8(der, key) {
  368. der.startSequence();
  369. if (PrivateKey.isPrivateKey(key)) {
  370. var version = 0;
  371. if (key.type === 'ed25519')
  372. version = 1;
  373. var vbuf = Buffer.from([version]);
  374. der.writeBuffer(vbuf, asn1.Ber.Integer);
  375. }
  376. der.startSequence();
  377. switch (key.type) {
  378. case 'rsa':
  379. der.writeOID('1.2.840.113549.1.1.1');
  380. if (PrivateKey.isPrivateKey(key))
  381. writePkcs8RSAPrivate(key, der);
  382. else
  383. writePkcs8RSAPublic(key, der);
  384. break;
  385. case 'dsa':
  386. der.writeOID('1.2.840.10040.4.1');
  387. if (PrivateKey.isPrivateKey(key))
  388. writePkcs8DSAPrivate(key, der);
  389. else
  390. writePkcs8DSAPublic(key, der);
  391. break;
  392. case 'ecdsa':
  393. der.writeOID('1.2.840.10045.2.1');
  394. if (PrivateKey.isPrivateKey(key))
  395. writePkcs8ECDSAPrivate(key, der);
  396. else
  397. writePkcs8ECDSAPublic(key, der);
  398. break;
  399. case 'ed25519':
  400. der.writeOID('1.3.101.112');
  401. if (PrivateKey.isPrivateKey(key))
  402. writePkcs8EdDSAPrivate(key, der);
  403. else
  404. writePkcs8EdDSAPublic(key, der);
  405. break;
  406. default:
  407. throw (new Error('Unsupported key type: ' + key.type));
  408. }
  409. der.endSequence();
  410. }
  411. function writePkcs8RSAPrivate(key, der) {
  412. der.writeNull();
  413. der.endSequence();
  414. der.startSequence(asn1.Ber.OctetString);
  415. der.startSequence();
  416. var version = Buffer.from([0]);
  417. der.writeBuffer(version, asn1.Ber.Integer);
  418. der.writeBuffer(key.part.n.data, asn1.Ber.Integer);
  419. der.writeBuffer(key.part.e.data, asn1.Ber.Integer);
  420. der.writeBuffer(key.part.d.data, asn1.Ber.Integer);
  421. der.writeBuffer(key.part.p.data, asn1.Ber.Integer);
  422. der.writeBuffer(key.part.q.data, asn1.Ber.Integer);
  423. if (!key.part.dmodp || !key.part.dmodq)
  424. utils.addRSAMissing(key);
  425. der.writeBuffer(key.part.dmodp.data, asn1.Ber.Integer);
  426. der.writeBuffer(key.part.dmodq.data, asn1.Ber.Integer);
  427. der.writeBuffer(key.part.iqmp.data, asn1.Ber.Integer);
  428. der.endSequence();
  429. der.endSequence();
  430. }
  431. function writePkcs8RSAPublic(key, der) {
  432. der.writeNull();
  433. der.endSequence();
  434. der.startSequence(asn1.Ber.BitString);
  435. der.writeByte(0x00);
  436. der.startSequence();
  437. der.writeBuffer(key.part.n.data, asn1.Ber.Integer);
  438. der.writeBuffer(key.part.e.data, asn1.Ber.Integer);
  439. der.endSequence();
  440. der.endSequence();
  441. }
  442. function writePkcs8DSAPrivate(key, der) {
  443. der.startSequence();
  444. der.writeBuffer(key.part.p.data, asn1.Ber.Integer);
  445. der.writeBuffer(key.part.q.data, asn1.Ber.Integer);
  446. der.writeBuffer(key.part.g.data, asn1.Ber.Integer);
  447. der.endSequence();
  448. der.endSequence();
  449. der.startSequence(asn1.Ber.OctetString);
  450. der.writeBuffer(key.part.x.data, asn1.Ber.Integer);
  451. der.endSequence();
  452. }
  453. function writePkcs8DSAPublic(key, der) {
  454. der.startSequence();
  455. der.writeBuffer(key.part.p.data, asn1.Ber.Integer);
  456. der.writeBuffer(key.part.q.data, asn1.Ber.Integer);
  457. der.writeBuffer(key.part.g.data, asn1.Ber.Integer);
  458. der.endSequence();
  459. der.endSequence();
  460. der.startSequence(asn1.Ber.BitString);
  461. der.writeByte(0x00);
  462. der.writeBuffer(key.part.y.data, asn1.Ber.Integer);
  463. der.endSequence();
  464. }
  465. function writeECDSACurve(key, der) {
  466. var curve = algs.curves[key.curve];
  467. if (curve.pkcs8oid) {
  468. /* This one has a name in pkcs#8, so just write the oid */
  469. der.writeOID(curve.pkcs8oid);
  470. } else {
  471. // ECParameters sequence
  472. der.startSequence();
  473. var version = Buffer.from([1]);
  474. der.writeBuffer(version, asn1.Ber.Integer);
  475. // FieldID sequence
  476. der.startSequence();
  477. der.writeOID('1.2.840.10045.1.1'); // prime-field
  478. der.writeBuffer(curve.p, asn1.Ber.Integer);
  479. der.endSequence();
  480. // Curve sequence
  481. der.startSequence();
  482. var a = curve.p;
  483. if (a[0] === 0x0)
  484. a = a.slice(1);
  485. der.writeBuffer(a, asn1.Ber.OctetString);
  486. der.writeBuffer(curve.b, asn1.Ber.OctetString);
  487. der.writeBuffer(curve.s, asn1.Ber.BitString);
  488. der.endSequence();
  489. der.writeBuffer(curve.G, asn1.Ber.OctetString);
  490. der.writeBuffer(curve.n, asn1.Ber.Integer);
  491. var h = curve.h;
  492. if (!h) {
  493. h = Buffer.from([1]);
  494. }
  495. der.writeBuffer(h, asn1.Ber.Integer);
  496. // ECParameters
  497. der.endSequence();
  498. }
  499. }
  500. function writePkcs8ECDSAPublic(key, der) {
  501. writeECDSACurve(key, der);
  502. der.endSequence();
  503. var Q = utils.ecNormalize(key.part.Q.data, true);
  504. der.writeBuffer(Q, asn1.Ber.BitString);
  505. }
  506. function writePkcs8ECDSAPrivate(key, der) {
  507. writeECDSACurve(key, der);
  508. der.endSequence();
  509. der.startSequence(asn1.Ber.OctetString);
  510. der.startSequence();
  511. var version = Buffer.from([1]);
  512. der.writeBuffer(version, asn1.Ber.Integer);
  513. der.writeBuffer(key.part.d.data, asn1.Ber.OctetString);
  514. der.startSequence(0xa1);
  515. var Q = utils.ecNormalize(key.part.Q.data, true);
  516. der.writeBuffer(Q, asn1.Ber.BitString);
  517. der.endSequence();
  518. der.endSequence();
  519. der.endSequence();
  520. }
  521. function writePkcs8EdDSAPublic(key, der) {
  522. der.endSequence();
  523. utils.writeBitString(der, key.part.A.data);
  524. }
  525. function writePkcs8EdDSAPrivate(key, der) {
  526. der.endSequence();
  527. der.startSequence(asn1.Ber.OctetString);
  528. var k = utils.mpNormalize(key.part.k.data);
  529. /* RFCs call for storing exactly 32 bytes, so strip any leading zeros */
  530. while (k.length > 32 && k[0] === 0x00)
  531. k = k.slice(1);
  532. der.writeBuffer(k, asn1.Ber.OctetString);
  533. der.endSequence();
  534. utils.writeBitString(der, key.part.A.data, asn1.Ber.Context | 1);
  535. }