eskdf.js 6.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162
  1. "use strict";
  2. Object.defineProperty(exports, "__esModule", { value: true });
  3. exports.eskdf = exports.deriveMainSeed = exports.pbkdf2 = exports.scrypt = void 0;
  4. const _assert_js_1 = require("./_assert.js");
  5. const hkdf_js_1 = require("./hkdf.js");
  6. const sha256_js_1 = require("./sha256.js");
  7. const pbkdf2_js_1 = require("./pbkdf2.js");
  8. const scrypt_js_1 = require("./scrypt.js");
  9. const utils_js_1 = require("./utils.js");
  10. // A tiny KDF for various applications like AES key-gen.
  11. // Uses HKDF in a non-standard way, so it's not "KDF-secure", only "PRF-secure".
  12. // Which is good enough: assume sha2-256 retained preimage resistance.
  13. const SCRYPT_FACTOR = 2 ** 19;
  14. const PBKDF2_FACTOR = 2 ** 17;
  15. // Scrypt KDF
  16. function scrypt(password, salt) {
  17. return (0, scrypt_js_1.scrypt)(password, salt, { N: SCRYPT_FACTOR, r: 8, p: 1, dkLen: 32 });
  18. }
  19. exports.scrypt = scrypt;
  20. // PBKDF2-HMAC-SHA256
  21. function pbkdf2(password, salt) {
  22. return (0, pbkdf2_js_1.pbkdf2)(sha256_js_1.sha256, password, salt, { c: PBKDF2_FACTOR, dkLen: 32 });
  23. }
  24. exports.pbkdf2 = pbkdf2;
  25. // Combines two 32-byte byte arrays
  26. function xor32(a, b) {
  27. (0, _assert_js_1.bytes)(a, 32);
  28. (0, _assert_js_1.bytes)(b, 32);
  29. const arr = new Uint8Array(32);
  30. for (let i = 0; i < 32; i++) {
  31. arr[i] = a[i] ^ b[i];
  32. }
  33. return arr;
  34. }
  35. function strHasLength(str, min, max) {
  36. return typeof str === 'string' && str.length >= min && str.length <= max;
  37. }
  38. /**
  39. * Derives main seed. Takes a lot of time. Prefer `eskdf` method instead.
  40. */
  41. function deriveMainSeed(username, password) {
  42. if (!strHasLength(username, 8, 255))
  43. throw new Error('invalid username');
  44. if (!strHasLength(password, 8, 255))
  45. throw new Error('invalid password');
  46. const scr = scrypt(password + '\u{1}', username + '\u{1}');
  47. const pbk = pbkdf2(password + '\u{2}', username + '\u{2}');
  48. const res = xor32(scr, pbk);
  49. scr.fill(0);
  50. pbk.fill(0);
  51. return res;
  52. }
  53. exports.deriveMainSeed = deriveMainSeed;
  54. /**
  55. * Converts protocol & accountId pair to HKDF salt & info params.
  56. */
  57. function getSaltInfo(protocol, accountId = 0) {
  58. // Note that length here also repeats two lines below
  59. // We do an additional length check here to reduce the scope of DoS attacks
  60. if (!(strHasLength(protocol, 3, 15) && /^[a-z0-9]{3,15}$/.test(protocol))) {
  61. throw new Error('invalid protocol');
  62. }
  63. // Allow string account ids for some protocols
  64. const allowsStr = /^password\d{0,3}|ssh|tor|file$/.test(protocol);
  65. let salt; // Extract salt. Default is undefined.
  66. if (typeof accountId === 'string') {
  67. if (!allowsStr)
  68. throw new Error('accountId must be a number');
  69. if (!strHasLength(accountId, 1, 255))
  70. throw new Error('accountId must be valid string');
  71. salt = (0, utils_js_1.toBytes)(accountId);
  72. }
  73. else if (Number.isSafeInteger(accountId)) {
  74. if (accountId < 0 || accountId > 2 ** 32 - 1)
  75. throw new Error('invalid accountId');
  76. // Convert to Big Endian Uint32
  77. salt = new Uint8Array(4);
  78. (0, utils_js_1.createView)(salt).setUint32(0, accountId, false);
  79. }
  80. else {
  81. throw new Error(`accountId must be a number${allowsStr ? ' or string' : ''}`);
  82. }
  83. const info = (0, utils_js_1.toBytes)(protocol);
  84. return { salt, info };
  85. }
  86. function countBytes(num) {
  87. if (typeof num !== 'bigint' || num <= BigInt(128))
  88. throw new Error('invalid number');
  89. return Math.ceil(num.toString(2).length / 8);
  90. }
  91. /**
  92. * Parses keyLength and modulus options to extract length of result key.
  93. * If modulus is used, adds 64 bits to it as per FIPS 186 B.4.1 to combat modulo bias.
  94. */
  95. function getKeyLength(options) {
  96. if (!options || typeof options !== 'object')
  97. return 32;
  98. const hasLen = 'keyLength' in options;
  99. const hasMod = 'modulus' in options;
  100. if (hasLen && hasMod)
  101. throw new Error('cannot combine keyLength and modulus options');
  102. if (!hasLen && !hasMod)
  103. throw new Error('must have either keyLength or modulus option');
  104. // FIPS 186 B.4.1 requires at least 64 more bits
  105. const l = hasMod ? countBytes(options.modulus) + 8 : options.keyLength;
  106. if (!(typeof l === 'number' && l >= 16 && l <= 8192))
  107. throw new Error('invalid keyLength');
  108. return l;
  109. }
  110. /**
  111. * Converts key to bigint and divides it by modulus. Big Endian.
  112. * Implements FIPS 186 B.4.1, which removes 0 and modulo bias from output.
  113. */
  114. function modReduceKey(key, modulus) {
  115. const _1 = BigInt(1);
  116. const num = BigInt('0x' + (0, utils_js_1.bytesToHex)(key)); // check for ui8a, then bytesToNumber()
  117. const res = (num % (modulus - _1)) + _1; // Remove 0 from output
  118. if (res < _1)
  119. throw new Error('expected positive number'); // Guard against bad values
  120. const len = key.length - 8; // FIPS requires 64 more bits = 8 bytes
  121. const hex = res.toString(16).padStart(len * 2, '0'); // numberToHex()
  122. const bytes = (0, utils_js_1.hexToBytes)(hex);
  123. if (bytes.length !== len)
  124. throw new Error('invalid length of result key');
  125. return bytes;
  126. }
  127. /**
  128. * ESKDF
  129. * @param username - username, email, or identifier, min: 8 characters, should have enough entropy
  130. * @param password - password, min: 8 characters, should have enough entropy
  131. * @example
  132. * const kdf = await eskdf('example-university', 'beginning-new-example');
  133. * const key = kdf.deriveChildKey('aes', 0);
  134. * console.log(kdf.fingerprint);
  135. * kdf.expire();
  136. */
  137. async function eskdf(username, password) {
  138. // We are using closure + object instead of class because
  139. // we want to make `seed` non-accessible for any external function.
  140. let seed = deriveMainSeed(username, password);
  141. function deriveCK(protocol, accountId = 0, options) {
  142. (0, _assert_js_1.bytes)(seed, 32);
  143. const { salt, info } = getSaltInfo(protocol, accountId); // validate protocol & accountId
  144. const keyLength = getKeyLength(options); // validate options
  145. const key = (0, hkdf_js_1.hkdf)(sha256_js_1.sha256, seed, salt, info, keyLength);
  146. // Modulus has already been validated
  147. return options && 'modulus' in options ? modReduceKey(key, options.modulus) : key;
  148. }
  149. function expire() {
  150. if (seed)
  151. seed.fill(1);
  152. seed = undefined;
  153. }
  154. // prettier-ignore
  155. const fingerprint = Array.from(deriveCK('fingerprint', 0))
  156. .slice(0, 6)
  157. .map((char) => char.toString(16).padStart(2, '0').toUpperCase())
  158. .join(':');
  159. return Object.freeze({ deriveChildKey: deriveCK, expire, fingerprint });
  160. }
  161. exports.eskdf = eskdf;
  162. //# sourceMappingURL=eskdf.js.map