package com.ruoyi.common.third.utils;

import org.bouncycastle.util.encoders.Hex;

import java.nio.charset.StandardCharsets;
import java.util.Arrays;

/**
 * SM4 CBC模式下加解密工具类
 */
public class SM4CbcUtil {

    /**
     * SM4 加密
     *
     * @param data 字符串明文
     * @param key 16进制密钥
     * @param iv CBC 模式的16进制 IV 数组
     * @return 16进制密文
     */
    public static String encrypt(String data, String key, String iv) {
        byte[] dataBytes = data.getBytes(StandardCharsets.UTF_8);
        byte[] keyBytes = Hex.decode(key);
        byte[] cryptBytes;
        byte[] ivBytes = Hex.decode(iv);
        cryptBytes = SM4Util.encryptData_CBC(ivBytes, keyBytes, dataBytes);
        return new String(Hex.encode(cryptBytes), StandardCharsets.UTF_8);
    }

    /**
     * SM4 解密
     *
     * @param data 16进制密文
     * @param key 16进制密钥
     * @param iv CBC 模式的16进制 IV 数组
     * @return 字符串明文
     */
    public static String decrypt(String data, String key, String iv) {
        byte[] dataBytes = Hex.decode(data.getBytes(StandardCharsets.UTF_8));
        byte[] keyBytes = Hex.decode(key);
        byte[] decryptBytes;
        byte[] ivBytes = Hex.decode(iv);
        decryptBytes = SM4Util.decryptData_CBC(ivBytes, keyBytes, dataBytes);

        if (decryptBytes.length > 0 && decryptBytes[decryptBytes.length - 1] == 0) {
            int until = decryptBytes.length - 1;
            while (until > 0 && decryptBytes[until - 1] == 0) until--;
            decryptBytes = Arrays.copyOfRange(decryptBytes, 0, until);
        }
        return new String(decryptBytes, StandardCharsets.UTF_8);
    }
}
