AesUtil.js 2.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869
  1. /**
  2. * 加密数据
  3. * @param {type} data 待加密的字符串
  4. * @param {type} keyStr 秘钥
  5. * @param {type} ivStr 向量
  6. * @returns {unresolved} 加密后的数据
  7. */
  8. /**
  9. *
  10. * @param {type=} keySize
  11. * @param {type=} iterationCount
  12. * @constructor
  13. */
  14. var AesUtil = function(keySize, iterationCount) {
  15. this.keySize = keySize / 32;
  16. this.iterationCount = iterationCount;
  17. };
  18. AesUtil.prototype.generateKey = function(salt, passPhrase) {
  19. var key = CryptoJS.PBKDF2(
  20. passPhrase,
  21. CryptoJS.enc.Hex.parse(salt),
  22. { keySize: this.keySize, iterations: this.iterationCount });
  23. return key;
  24. }
  25. AesUtil.prototype.encrypt = function(salt, iv, passPhrase, plainText) {
  26. var key = this.generateKey(salt, passPhrase);
  27. var encrypted = CryptoJS.AES.encrypt(
  28. plainText,
  29. key,
  30. { iv: CryptoJS.enc.Hex.parse(iv) });
  31. return encrypted.ciphertext.toString(CryptoJS.enc.Base64);
  32. }
  33. AesUtil.prototype.decrypt = function(salt, iv, passPhrase, cipherText) {
  34. var key = this.generateKey(salt, passPhrase);
  35. var cipherParams = CryptoJS.lib.CipherParams.create({
  36. ciphertext: CryptoJS.enc.Base64.parse(cipherText)
  37. });
  38. var decrypted = CryptoJS.AES.decrypt(
  39. cipherParams,
  40. key,
  41. { iv: CryptoJS.enc.Hex.parse(iv) });
  42. return decrypted.toString(CryptoJS.enc.Utf8);
  43. }
  44. AesUtil.prototype.aesEncrypt = function(data, keyStr, ivStr) {
  45. var sendData = CryptoJS.enc.Utf8.parse(data);
  46. var key = CryptoJS.enc.Utf8.parse(keyStr);
  47. var iv = CryptoJS.enc.Utf8.parse(ivStr);
  48. var encrypted = CryptoJS.AES.encrypt(sendData, key,{iv:iv,mode:CryptoJS.mode.CBC,padding:CryptoJS.pad.ZeroPadding});
  49. return CryptoJS.enc.Base64.stringify(encrypted.ciphertext);
  50. };
  51. /**
  52. *
  53. * @param {type} data BASE64的数据
  54. * @param {type} key 解密秘钥
  55. * @param {type} iv 向量
  56. * @returns {undefined}
  57. */
  58. AesUtil.prototype.aesDecrypt = function(data, keyStr, ivStr) {
  59. var key = CryptoJS.enc.Utf8.parse(keyStr);
  60. var iv = CryptoJS.enc.Utf8.parse(ivStr);
  61. //解密的是基于BASE64的数据,此处data是BASE64数据
  62. var decrypted = CryptoJS.AES.decrypt(data, key, {iv: iv, mode: CryptoJS.mode.CBC, padding: CryptoJS.pad.ZeroPadding});
  63. return decrypted.toString(CryptoJS.enc.Utf8);
  64. };