import { cryptoFramework } from '@kit.CryptoArchitectureKit';
import { buffer, util } from '@kit.ArkTS';


export const base = new util.Base64Helper();

export class AESEncryptionDecryption {

  // 字节流转成可理解的字符串
  static uint8ArrayToString(array: Uint8Array) {
    // 将UTF-8编码转换成Unicode编码
    let out: string = '';
    let index: number = 0;
    let len: number = array.length;
    while (index < len) {
      let character = array[index++];
      switch (character >> 4) {
        case 0:
        case 1:
        case 2:
        case 3:
        case 4:
        case 5:
        case 6:
        case 7:
          out += String.fromCharCode(character);
          break;
        case 12:
        case 13:
          out += String.fromCharCode(((character & 0x1F) << 6) | (array[index++] & 0x3F));
          break;
        case 14:
          out += String.fromCharCode(((character & 0x0F) << 12) | ((array[index++] & 0x3F) << 6) |
            ((array[index++] & 0x3F) << 0));
          break;
        default:
          break;
      }
    }
    return out;
  }

  // 字符串转成字节流
  static stringToUint8Array(str: string) {
    return new Uint8Array(buffer.from(str, 'utf-8').buffer);
  }

  // 获取密钥
  static async  getKey() {
    let symAlgName = 'AES128';
    let symKeyGenerator = cryptoFramework.createSymKeyGenerator(symAlgName);
    let dataUint8Array = AESEncryptionDecryption.stringToUint8Array('Whh82GtW/EVjBkD8');
    let keyBlob: cryptoFramework.DataBlob = { data: dataUint8Array };
    let promiseSymKey = await symKeyGenerator.convertKey(keyBlob);
    let key = base.encodeToStringSync(promiseSymKey.getEncoded().data); // 将密钥转换为base64存储
    return key;
  }

  // 加密
  static async aesEncrypt(text: string, puKey: string): Promise<string> {
    let globalResult = '';
    try {
      let cipherAlgName = 'AES128|ECB|PKCS7';
      let globalCipher = cryptoFramework.createCipher(cipherAlgName);
      let symAlgName = 'AES128';
      let symKeyGenerator = cryptoFramework.createSymKeyGenerator(symAlgName);
      // let dataUint8Array = base.decodeSync(puKey);
      let dataUint8Array = AESEncryptionDecryption.stringToUint8Array(puKey);
      let keyBlob: cryptoFramework.DataBlob = { data: dataUint8Array };
      let promiseSymKey = await symKeyGenerator.convertKey(keyBlob);
      await globalCipher.init(cryptoFramework.CryptoMode.ENCRYPT_MODE, promiseSymKey, null);
      let result = await globalCipher.doFinal({ data: AESEncryptionDecryption.stringToUint8Array(text) });
      globalResult = base.encodeToStringSync(result.data);
      console.info('加密后的明文:' + globalResult);
    } catch (err) {
      console.info('加密错误:' +err.message);
    }
    return globalResult;
  }
  // 使用 AES 密钥加密数据

  static encryptMessage(symKey: cryptoFramework.SymKey, plainText: cryptoFramework.DataBlob) {

    let cipher = cryptoFramework.createCipher('AES128|ECB|PKCS7');

    cipher.initSync(cryptoFramework.CryptoMode.ENCRYPT_MODE, symKey, null); // ECB模式params为null。

    let cipherData = cipher.doFinalSync(plainText);

    return cipherData;

  }

  // 解密
  static async aesDecrypt(text: string, key: string) {
    let globalResult = '';
    try {
      let cipherAlgName = 'AES128|ECB|PKCS7';
      let globalCipher = cryptoFramework.createCipher(cipherAlgName);
      let symAlgName = 'AES128';
      let symKeyGenerator = cryptoFramework.createSymKeyGenerator(symAlgName);
      let dataUint8Array = base.decodeSync(key);
      let keyBlob: cryptoFramework.DataBlob = { data: dataUint8Array };
      let promiseSymKey = await symKeyGenerator.convertKey(keyBlob);
      await globalCipher.init(cryptoFramework.CryptoMode.DECRYPT_MODE, promiseSymKey, null);
      let plainText: cryptoFramework.DataBlob = { data: base.decodeSync(text) };
      let result = await globalCipher.doFinal(plainText);
      globalResult = AESEncryptionDecryption.uint8ArrayToString(result.data);
      console.info('解密后的明文:' + globalResult);
    } catch (err) {
      console.info(err.message);
    }
  }
}

