pbkdf2.js 1.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950
  1. /*!
  2. * Crypto-JS v1.1.0
  3. * http://code.google.com/p/crypto-js/
  4. * Copyright (c) 2009, Jeff Mott. All rights reserved.
  5. * http://code.google.com/p/crypto-js/wiki/License
  6. */
  7. (function(){
  8. // Shortcut
  9. var util = Crypto.util;
  10. Crypto.PBKDF2 = function (password, salt, keylen, options) {
  11. // Defaults
  12. var hasher = options && options.hasher || Crypto.SHA1,
  13. iterations = options && options.iterations || 1;
  14. // Pseudo-random function
  15. function PRF(password, salt) {
  16. return Crypto.HMAC(hasher, salt, password, { asBytes: true });
  17. }
  18. // Generate key
  19. var derivedKeyBytes = [],
  20. blockindex = 1;
  21. while (derivedKeyBytes.length < keylen) {
  22. var block = PRF(password, salt + util.bytesToString(
  23. util.wordsToBytes([blockindex])));
  24. for (var u = block, i = 1; i < iterations; i++) {
  25. u = PRF(password, util.bytesToString(u));
  26. for (var j = 0; j < block.length; j++) block[j] ^= u[j];
  27. }
  28. derivedKeyBytes = derivedKeyBytes.concat(block);
  29. blockindex++;
  30. }
  31. // Truncate excess bytes
  32. derivedKeyBytes.length = keylen;
  33. return options && options.asBytes ? derivedKeyBytes :
  34. options && options.asString ? util.bytesToString(derivedKeyBytes) :
  35. util.bytesToHex(derivedKeyBytes);
  36. };
  37. })();