cipher.js 2.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384
  1. import { encrypt, decrypt } from 'crypto-js/aes';
  2. import { parse as parseUtf8 } from 'crypto-js/enc-utf8';
  3. import pkcs7 from 'crypto-js/pad-pkcs7';
  4. import md5 from 'crypto-js/md5';
  5. import UTF8 from 'crypto-js/enc-utf8';
  6. import Base64 from 'crypto-js/enc-base64';
  7. import * as CryptoJS from 'crypto-js';
  8. class AesEncryption {
  9. constructor(opt = {}) {
  10. const { key, iv } = opt;
  11. if (key) {
  12. this.key = parseUtf8(key);
  13. }
  14. if (iv) {
  15. this.iv = parseUtf8(iv);
  16. }
  17. }
  18. get getOptions() {
  19. return {
  20. mode: CryptoJS.mode.CBC,
  21. padding: pkcs7,
  22. iv: this.iv,
  23. };
  24. }
  25. encryptByAES(cipherText) {
  26. return encrypt(cipherText, this.key, this.getOptions).toString();
  27. }
  28. decryptByAES(cipherText) {
  29. return decrypt(cipherText, this.key, this.getOptions).toString(UTF8);
  30. }
  31. // 将 Uint8Array 转换为 CryptoJS.lib.WordArray
  32. static uint8ArrayToWordArray(uint8Array) {
  33. const words = [];
  34. for (let i = 0; i < uint8Array.length; i += 4) {
  35. let word = 0;
  36. for (let j = 0; j < 4 && i + j < uint8Array.length; j++) {
  37. word |= (uint8Array[i + j] & 0xff) << (24 - 8 * j);
  38. }
  39. words.push(word);
  40. }
  41. return CryptoJS.lib.WordArray.create(words, uint8Array.length);
  42. }
  43. // 将 CryptoJS.lib.WordArray 转换为 Uint8Array
  44. static wordArrayToUint8Array(wordArray) {
  45. const words = wordArray.words;
  46. const sigBytes = wordArray.sigBytes;
  47. const uint8Array = new Uint8Array(sigBytes);
  48. for (let i = 0; i < sigBytes; i++) {
  49. const byte = (words[i >>> 2] >>> (24 - (i % 4) * 8)) & 0xff;
  50. uint8Array[i] = byte;
  51. }
  52. return uint8Array;
  53. }
  54. }
  55. function encryptByBase64(cipherText) {
  56. return UTF8.parse(cipherText).toString(Base64);
  57. }
  58. function decodeByBase64(cipherText) {
  59. return Base64.parse(cipherText).toString(UTF8);
  60. }
  61. function encryptByMd5(password) {
  62. return md5(password).toString();
  63. }
  64. function getLoginCipher() {
  65. return {
  66. key: '_11111000001111@',
  67. iv: '@11111000001111_',
  68. };
  69. }
  70. // 导出需要的函数和类
  71. export { AesEncryption, encryptByBase64, decodeByBase64, encryptByMd5, getLoginCipher };