eskdf.js 6.4 KB

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