eskdf.js 6.1 KB

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