crypto.js 2.1 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980
  1. import CryptoJS from 'crypto-js'
  2. export default class crypto {
  3. // 使用AesUtil.genAesKey()生成,需和后端配置保持一致
  4. static aesKey = "uQFw4pOEtPdzU4LP3ywbaUtoGMHywnUi";
  5. // 使用DesUtil.genDesKey()生成,需和后端配置保持一致
  6. static desKey = "XHHUNdnCka60Y5zJ";
  7. /**
  8. * aes 加密方法
  9. * @param data
  10. * @returns {*}
  11. */
  12. static encrypt(data) {
  13. return this.encryptAES(data, this.aesKey);
  14. }
  15. /**
  16. * aes 解密方法
  17. * @param data
  18. * @returns {*}
  19. */
  20. static decrypt(data) {
  21. return this.decryptAES(data, this.aesKey);
  22. }
  23. /**
  24. * aes 加密方法,同java:AesUtil.encryptToBase64(text, aesKey);
  25. */
  26. static encryptAES(data, key) {
  27. const dataBytes = CryptoJS.enc.Utf8.parse(data);
  28. const keyBytes = CryptoJS.enc.Utf8.parse(key);
  29. const encrypted = CryptoJS.AES.encrypt(dataBytes, keyBytes, {
  30. iv: keyBytes,
  31. mode: CryptoJS.mode.CBC,
  32. padding: CryptoJS.pad.Pkcs7
  33. });
  34. return CryptoJS.enc.Base64.stringify(encrypted.ciphertext);
  35. }
  36. /**
  37. * aes 解密方法,同java:AesUtil.decryptFormBase64ToString(encrypt, aesKey);
  38. */
  39. static decryptAES(data, key) {
  40. const keyBytes = CryptoJS.enc.Utf8.parse(key);
  41. const decrypted = CryptoJS.AES.decrypt(data, keyBytes, {
  42. iv: keyBytes,
  43. mode: CryptoJS.mode.CBC,
  44. padding: CryptoJS.pad.Pkcs7
  45. });
  46. return CryptoJS.enc.Utf8.stringify(decrypted);
  47. }
  48. /**
  49. * des 加密方法,同java:DesUtil.encryptToBase64(text, desKey)
  50. */
  51. static encryptDES(data, key) {
  52. const keyHex = CryptoJS.enc.Utf8.parse(key);
  53. const encrypted = CryptoJS.DES.encrypt(data, keyHex, {
  54. mode: CryptoJS.mode.ECB,
  55. padding: CryptoJS.pad.Pkcs7
  56. });
  57. return encrypted.toString();
  58. }
  59. /**
  60. * des 解密方法,同java:DesUtil.decryptFormBase64(encryptBase64, desKey);
  61. */
  62. static decryptDES(data, key) {
  63. const keyHex = CryptoJS.enc.Utf8.parse(key);
  64. const decrypted = CryptoJS.DES.decrypt({
  65. ciphertext: CryptoJS.enc.Base64.parse(data)
  66. }, keyHex, {
  67. mode: CryptoJS.mode.ECB,
  68. padding: CryptoJS.pad.Pkcs7
  69. });
  70. return decrypted.toString(CryptoJS.enc.Utf8);
  71. }
  72. }