pbkdf2.js 1.6 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849
  1. /**
  2. * A **Password-Based Key-Derivation Function** is designed to create
  3. * a sequence of bytes suitible as a **key** from a human-rememberable
  4. * password.
  5. *
  6. * @_subsection: api/crypto:Passwords [about-pbkdf]
  7. */
  8. import { pbkdf2Sync } from "./crypto.js";
  9. import { getBytes, hexlify } from "../utils/index.js";
  10. let locked = false;
  11. const _pbkdf2 = function (password, salt, iterations, keylen, algo) {
  12. return pbkdf2Sync(password, salt, iterations, keylen, algo);
  13. };
  14. let __pbkdf2 = _pbkdf2;
  15. /**
  16. * Return the [[link-pbkdf2]] for %%keylen%% bytes for %%password%% using
  17. * the %%salt%% and using %%iterations%% of %%algo%%.
  18. *
  19. * This PBKDF is outdated and should not be used in new projects, but is
  20. * required to decrypt older files.
  21. *
  22. * @example:
  23. * // The password must be converted to bytes, and it is generally
  24. * // best practices to ensure the string has been normalized. Many
  25. * // formats explicitly indicate the normalization form to use.
  26. * password = "hello"
  27. * passwordBytes = toUtf8Bytes(password, "NFKC")
  28. *
  29. * salt = id("some-salt")
  30. *
  31. * // Compute the PBKDF2
  32. * pbkdf2(passwordBytes, salt, 1024, 16, "sha256")
  33. * //_result:
  34. */
  35. export function pbkdf2(_password, _salt, iterations, keylen, algo) {
  36. const password = getBytes(_password, "password");
  37. const salt = getBytes(_salt, "salt");
  38. return hexlify(__pbkdf2(password, salt, iterations, keylen, algo));
  39. }
  40. pbkdf2._ = _pbkdf2;
  41. pbkdf2.lock = function () { locked = true; };
  42. pbkdf2.register = function (func) {
  43. if (locked) {
  44. throw new Error("pbkdf2 is locked");
  45. }
  46. __pbkdf2 = func;
  47. };
  48. Object.freeze(pbkdf2);
  49. //# sourceMappingURL=pbkdf2.js.map