package com.duben.microtribe.utils;


import com.duben.microtribe.common.Constant;
import com.duben.microtribe.BuildConfig;

import javax.crypto.Cipher;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;

import Decoder.BASE64Decoder;
import Decoder.BASE64Encoder;


public class AESUtils {

    private static final String vis = MD5.GetMD5Code("helivideo_2023").substring(8, 24);
    public static String CIPHER_ALGORITHM = "AES/CBC/PKCS5Padding"; // optional value AES/DES/DESede

    private static SecretKeySpec getKey(String strKey) throws Exception {
        byte[] arrBTmp = strKey.getBytes();
        byte[] arrB = new byte[16]; // 创建一个空的16位字节数组（默认值为0）

        for (int i = 0; i < arrBTmp.length && i < arrB.length; i++) {
            arrB[i] = arrBTmp[i];
        }
        SecretKeySpec skeySpec = new SecretKeySpec(arrB, "AES");
        return skeySpec;
    }

    public static String encrypt(String message, String key) {
        try {
            SecretKeySpec skeySpec = getKey(key);
            Cipher cipher = Cipher.getInstance(CIPHER_ALGORITHM);
            IvParameterSpec iv = new IvParameterSpec(vis.getBytes());
            cipher.init(Cipher.ENCRYPT_MODE, skeySpec, iv);
            byte[] encrypted = cipher.doFinal(message.getBytes("UTF-8"));
            return new BASE64Encoder().encode(encrypted);
        } catch (Exception e) {
        }
        return "";
    }


    public static String detrypt(String message, String key) {
        try {
            byte[] res = new BASE64Decoder().decodeBuffer(message);
            SecretKeySpec skeySpec = getKey(key);
            Cipher cipher = Cipher.getInstance(CIPHER_ALGORITHM);
            IvParameterSpec iv = new IvParameterSpec(vis.getBytes());
            cipher.init(Cipher.DECRYPT_MODE, skeySpec, iv);
            byte[] detrypted = cipher.doFinal(res);
            return new String(detrypted, "UTF-8");
        } catch (Exception e) {
        }
        return "";
    }

    private static String getBK1() {
        return BuildConfig.AppKeyPre;
    }

    private static String getBK2() {
        return "nnnnnn";
    }

    private static String getBK3(int size) {
        StringBuffer sb = new StringBuffer();
        for (int i = 1; i <= size; i++) {
            sb.append(i);
        }
        return sb.toString();
    }

    public static String getDefaultKey() {
        StringBuffer sb = new StringBuffer();
        sb.append(getBK1())
                .append(getBK2())
                .append(getBK3(6));
        return sb.toString();
    }
}
