crypto.ts 1.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566
  1. import CryptoJS from 'crypto-js';
  2. /**
  3. * 随机生成32位的字符串
  4. * @returns {string}
  5. */
  6. const generateRandomString = () => {
  7. const characters = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789';
  8. let result = '';
  9. const charactersLength = characters.length;
  10. for (let i = 0; i < 32; i++) {
  11. result += characters.charAt(Math.floor(Math.random() * charactersLength));
  12. }
  13. return result;
  14. };
  15. /**
  16. * 随机生成aes 密钥
  17. * @returns {string}
  18. */
  19. export const generateAesKey = () => {
  20. return CryptoJS.enc.Utf8.parse(generateRandomString());
  21. };
  22. /**
  23. * 加密base64
  24. * @returns {string}
  25. */
  26. export const encryptBase64 = (str: CryptoJS.lib.WordArray) => {
  27. return CryptoJS.enc.Base64.stringify(str);
  28. };
  29. /**
  30. * 解密base64
  31. */
  32. export const decryptBase64 = (str: string) => {
  33. return CryptoJS.enc.Base64.parse(str);
  34. };
  35. /**
  36. * 使用密钥对数据进行加密
  37. * @param message
  38. * @param aesKey
  39. * @returns {string}
  40. */
  41. export const encryptWithAes = (message: string, aesKey: CryptoJS.lib.WordArray) => {
  42. const encrypted = CryptoJS.AES.encrypt(message, aesKey, {
  43. mode: CryptoJS.mode.ECB,
  44. padding: CryptoJS.pad.Pkcs7
  45. });
  46. return encrypted.toString();
  47. };
  48. /**
  49. * 使用密钥对数据进行解密
  50. * @param message
  51. * @param aesKey
  52. * @returns {string}
  53. */
  54. export const decryptWithAes = (message: string, aesKey: CryptoJS.lib.WordArray) => {
  55. const decrypted = CryptoJS.AES.decrypt(message, aesKey, {
  56. mode: CryptoJS.mode.ECB,
  57. padding: CryptoJS.pad.Pkcs7
  58. });
  59. return decrypted.toString(CryptoJS.enc.Utf8);
  60. };