pbkdf2.js 1.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354
  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} 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 || 1000;
  23. if (length < 0 || count < 0) {
  24. throw sjcl.exception.invalid("invalid params to pbkdf2");
  25. }
  26. if (typeof password === "string") {
  27. password = sjcl.codec.utf8String.toBits(password);
  28. }
  29. Prff = Prff || sjcl.misc.hmac;
  30. var prf = new Prff(password),
  31. u, ui, i, j, k, out = [], b = sjcl.bitArray;
  32. for (k = 1; 32 * out.length < (length || 1); k++) {
  33. u = ui = prf.encrypt(b.concat(salt,[k]));
  34. for (i=1; i<count; i++) {
  35. ui = prf.encrypt(ui);
  36. for (j=0; j<ui.length; j++) {
  37. u[j] ^= ui[j];
  38. }
  39. }
  40. out = out.concat(u);
  41. }
  42. if (length) { out = b.clamp(out, length); }
  43. return out;
  44. };