package com.awspaas.user.apps.donenow_sys.job;

import com.actionsoft.bpms.schedule.IJob;
import com.actionsoft.sdk.local.SDK;
import com.actionsoft.sdk.local.api.Logger;
import jxl.write.WritableWorkbook;
import org.quartz.JobExecutionContext;
import org.quartz.JobExecutionException;

import javax.crypto.KeyGenerator;
import javax.crypto.SecretKey;
import java.security.SecureRandom;
import java.util.Base64;
public class exectest1 implements IJob {
    private static final Logger logger = SDK.getLogAPI().getLogger(exectest1.class);//记录日志

    /**
     *
     * @param jobExecutionContext
     * @throws JobExecutionException
     */
    @Override
    public void execute(JobExecutionContext jobExecutionContext) throws JobExecutionException {

        WritableWorkbook wwb = null;

        // 生成 AES 密钥
        SecretKey secretKey = null;
        try {
            secretKey = generateAESKey(KEY_SIZE);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
        String base64Key = Base64.getEncoder().encodeToString(secretKey.getEncoded());
        String hexKey = bytesToHex(secretKey.getEncoded());

        System.out.println("🔹 AES 密钥 (Base64):");
        System.out.println(base64Key);
        System.out.println("\n🔹 AES 密钥 (HEX):");
        System.out.println(hexKey);

        // CBC 模式需要 IV
        byte[] iv = generateIV();
        String base64IV = Base64.getEncoder().encodeToString(iv);
        String hexIV = bytesToHex(iv);

        System.out.println("\n\n🔸 CBC 初始化向量 IV (Base64):");
        System.out.println(base64IV);
        System.out.println("\n🔸 CBC 初始化向量 IV (HEX):");
        System.out.println(hexIV);
    }

    // AES 支持的密钥长度：128、192、256 位
    private static final int KEY_SIZE = 128; // 推荐使用256位
    // IV 长度固定为16字节（128位）
    private static final int IV_SIZE = 16;


    /**
     * 生成指定长度的 AES 密钥
     */
    public static SecretKey generateAESKey(int keySizeInBits) throws Exception {
        KeyGenerator kg = KeyGenerator.getInstance("AES");
        kg.init(keySizeInBits); // 可选值：128, 192, 256
        return kg.generateKey();
    }

    /**
     * 生成 16 字节的随机 IV（仅用于 CBC 等模式）
     */
    public static byte[] generateIV() {
        byte[] iv = new byte[IV_SIZE];
        new SecureRandom().nextBytes(iv);
        return iv;
    }

    /**
     * 将 byte[] 转换为十六进制字符串
     */
    public static String bytesToHex(byte[] bytes) {
        StringBuilder sb = new StringBuilder();
        for (byte b : bytes) {
            sb.append(String.format("%02x", b));
        }
        return sb.toString();
    }

}
