package cn.hanghui.outapi.platform.common.utils;

import cn.hanghui.outapi.platform.common.entity.rest.RespCodeEnum;
import cn.hanghui.outapi.platform.common.exception.CommonException;
import cn.hutool.crypto.Mode;
import cn.hutool.crypto.Padding;
import cn.hutool.crypto.symmetric.SM4;
import org.apache.commons.codec.DecoderException;
import org.apache.commons.codec.binary.Hex;

import java.nio.charset.StandardCharsets;

public class Sm4Util {

    /**
     * 加密
     *
     * @param plainText 明文
     * @param key       密钥
     * @param iv        初始向量
     * @return 密文
     */
    public static String encode(String plainText, String key, byte[] iv) {
        SM4 sm4 =new SM4(Mode.OFB, Padding.NoPadding, key.getBytes(StandardCharsets.UTF_8), iv);
        byte[] encrypt = sm4.encrypt(plainText);
        return Hex.encodeHexString(encrypt);
    }

    /**
     * 解密
     *
     * @param secretText 密文
     * @param key        密钥
     * @param iv         初始向量
     * @return 明文
     */
    public static String decode(String secretText, String key, byte[] iv) {
        try {
            SM4 sm4 = new SM4(Mode.OFB, Padding.NoPadding,
                    key.getBytes(StandardCharsets.UTF_8), iv);
            byte[] data = Hex.decodeHex(secretText.toCharArray());
            byte[] decryptData = sm4.decrypt(data);
            return new String(decryptData);
        } catch (DecoderException e) {
            throw new CommonException(RespCodeEnum.DATA_ENCODE_FAILED);
        }
    }


}
