Source: pbkdf2.js

  1. /** @fileOverview Password-based key-derivation function, version 2.0.
  2. *
  3. * @author Emily Stark
  4. * @author Mike Hamburg
  5. * @author Dan Boneh
  6. */
  7. /** Password-Based Key-Derivation Function, version 2.0.
  8. *
  9. * Generate keys from passwords using PBKDF2-HMAC-SHA256.
  10. *
  11. * This is the method specified by RSA's PKCS #5 standard.
  12. *
  13. * @param {bitArray|String} password The password.
  14. * @param {bitArray|String} salt The salt. Should have lots of entropy.
  15. * @param {Number} [count=1000] The number of iterations. Higher numbers make the function slower but more secure.
  16. * @param {Number} [length] The length of the derived key. Defaults to the
  17. output size of the hash function.
  18. * @param {Object} [Prff=sjcl.misc.hmac] The pseudorandom function family.
  19. * @return {bitArray} the derived key.
  20. */
  21. sjcl.misc.pbkdf2 = function (password, salt, count, length, Prff) {
  22. count = count || 10000;
  23. if (length < 0 || count < 0) {
  24. throw new sjcl.exception.invalid("invalid params to pbkdf2");
  25. }
  26. if (typeof password === "string") {
  27. password = sjcl.codec.utf8String.toBits(password);
  28. }
  29. if (typeof salt === "string") {
  30. salt = sjcl.codec.utf8String.toBits(salt);
  31. }
  32. Prff = Prff || sjcl.misc.hmac;
  33. var prf = new Prff(password),
  34. u, ui, i, j, k, out = [], b = sjcl.bitArray;
  35. for (k = 1; 32 * out.length < (length || 1); k++) {
  36. u = ui = prf.encrypt(b.concat(salt,[k]));
  37. for (i=1; i<count; i++) {
  38. ui = prf.encrypt(ui);
  39. for (j=0; j<ui.length; j++) {
  40. u[j] ^= ui[j];
  41. }
  42. }
  43. out = out.concat(u);
  44. }
  45. if (length) { out = b.clamp(out, length); }
  46. return out;
  47. };