|
@@ -0,0 +1,84 @@
|
|
|
+import { encrypt, decrypt } from 'crypto-js/aes';
|
|
|
+import { parse as parseUtf8 } from 'crypto-js/enc-utf8';
|
|
|
+import pkcs7 from 'crypto-js/pad-pkcs7';
|
|
|
+import md5 from 'crypto-js/md5';
|
|
|
+import UTF8 from 'crypto-js/enc-utf8';
|
|
|
+import Base64 from 'crypto-js/enc-base64';
|
|
|
+import * as CryptoJS from 'crypto-js';
|
|
|
+
|
|
|
+class AesEncryption {
|
|
|
+ constructor(opt = {}) {
|
|
|
+ const { key, iv } = opt;
|
|
|
+ if (key) {
|
|
|
+ this.key = parseUtf8(key);
|
|
|
+ }
|
|
|
+ if (iv) {
|
|
|
+ this.iv = parseUtf8(iv);
|
|
|
+ }
|
|
|
+ }
|
|
|
+
|
|
|
+ get getOptions() {
|
|
|
+ return {
|
|
|
+ mode: CryptoJS.mode.CBC,
|
|
|
+ padding: pkcs7,
|
|
|
+ iv: this.iv,
|
|
|
+ };
|
|
|
+ }
|
|
|
+
|
|
|
+ encryptByAES(cipherText) {
|
|
|
+ return encrypt(cipherText, this.key, this.getOptions).toString();
|
|
|
+ }
|
|
|
+
|
|
|
+ decryptByAES(cipherText) {
|
|
|
+ return decrypt(cipherText, this.key, this.getOptions).toString(UTF8);
|
|
|
+ }
|
|
|
+
|
|
|
+ // 将 Uint8Array 转换为 CryptoJS.lib.WordArray
|
|
|
+ static uint8ArrayToWordArray(uint8Array) {
|
|
|
+ const words = [];
|
|
|
+ for (let i = 0; i < uint8Array.length; i += 4) {
|
|
|
+ let word = 0;
|
|
|
+ for (let j = 0; j < 4 && i + j < uint8Array.length; j++) {
|
|
|
+ word |= (uint8Array[i + j] & 0xff) << (24 - 8 * j);
|
|
|
+ }
|
|
|
+ words.push(word);
|
|
|
+ }
|
|
|
+ return CryptoJS.lib.WordArray.create(words, uint8Array.length);
|
|
|
+ }
|
|
|
+
|
|
|
+ // 将 CryptoJS.lib.WordArray 转换为 Uint8Array
|
|
|
+ static wordArrayToUint8Array(wordArray) {
|
|
|
+ const words = wordArray.words;
|
|
|
+ const sigBytes = wordArray.sigBytes;
|
|
|
+ const uint8Array = new Uint8Array(sigBytes);
|
|
|
+
|
|
|
+ for (let i = 0; i < sigBytes; i++) {
|
|
|
+ const byte = (words[i >>> 2] >>> (24 - (i % 4) * 8)) & 0xff;
|
|
|
+ uint8Array[i] = byte;
|
|
|
+ }
|
|
|
+
|
|
|
+ return uint8Array;
|
|
|
+ }
|
|
|
+}
|
|
|
+
|
|
|
+function encryptByBase64(cipherText) {
|
|
|
+ return UTF8.parse(cipherText).toString(Base64);
|
|
|
+}
|
|
|
+
|
|
|
+function decodeByBase64(cipherText) {
|
|
|
+ return Base64.parse(cipherText).toString(UTF8);
|
|
|
+}
|
|
|
+
|
|
|
+function encryptByMd5(password) {
|
|
|
+ return md5(password).toString();
|
|
|
+}
|
|
|
+
|
|
|
+function getLoginCipher() {
|
|
|
+ return {
|
|
|
+ key: '_11111000001111@',
|
|
|
+ iv: '@11111000001111_',
|
|
|
+ };
|
|
|
+}
|
|
|
+
|
|
|
+// 导出需要的函数和类
|
|
|
+export { AesEncryption, encryptByBase64, decodeByBase64, encryptByMd5, getLoginCipher };
|