crypto.ts 1.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445
  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. * 随机生成aes 密钥
  24. * @returns {string}
  25. */
  26. export const encryptBase64 = (str: string) => {
  27. return CryptoJS.enc.Base64.stringify(str);
  28. };
  29. /**
  30. * 使用密钥对数据进行加密
  31. * @param message
  32. * @param aesKey
  33. * @returns {string}
  34. */
  35. export const encryptWithAes = (message: string, aesKey: CryptoJS.lib.WordArray) => {
  36. const encrypted = CryptoJS.AES.encrypt(message, aesKey, {
  37. mode: CryptoJS.mode.ECB,
  38. padding: CryptoJS.pad.Pkcs7
  39. });
  40. return encrypted.toString();
  41. };