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

import org.apache.commons.codec.binary.Base64;

import javax.crypto.BadPaddingException;
import javax.crypto.Cipher;
import javax.crypto.IllegalBlockSizeException;
import javax.crypto.NoSuchPaddingException;
import javax.crypto.SecretKey;
import javax.crypto.SecretKeyFactory;
import javax.crypto.spec.DESedeKeySpec;
import java.nio.charset.Charset;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import java.security.spec.InvalidKeySpecException;

/**
 * @author shisl
 * @package cn.hanghui.outapi.platform.common.utils
 * @class DESUtil
 * @date 2024/1/17 上午9:31
 * @description
 */
public class DESUtil {


    private static final String KEY_ALGORITHM = "DESede";
    private static final String CIPHER_ALGORITHM = "DESede/ECB/PKCS5Padding";
    private static final String ENCODING = "UTF-8";

    /**
     * 加密
     *
     * @param data 参数 json 字符串 * @param key 平台提供的 deskey * @return
     */
    public static String encrypt(String data, String key) {
        byte[] encrypt =
                encrypt(data.getBytes(Charset.forName(ENCODING)), key);
        return encrypt == null ? null :
                Base64.encodeBase64String(encrypt);
    }

    private static byte[] encrypt(byte[] data, String key) {
        try {
            //实例化 Des 密钥
            DESedeKeySpec dks = new DESedeKeySpec(key.getBytes()); //实例化密钥工厂
            SecretKeyFactory keyFactory = SecretKeyFactory.getInstance(KEY_ALGORITHM); //生成密钥
            SecretKey secretKey = keyFactory.generateSecret(dks);
            //实例化
            Cipher cipher = Cipher.getInstance(CIPHER_ALGORITHM); //初始化，设置为加密模式
            cipher.init(Cipher.ENCRYPT_MODE, secretKey);
            return cipher.doFinal(data);
        } catch (InvalidKeyException e) {
            e.printStackTrace();
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        } catch (InvalidKeySpecException e) {
            e.printStackTrace();
        } catch (NoSuchPaddingException e) {
            e.printStackTrace();
        } catch (IllegalBlockSizeException e) {
            e.printStackTrace();
        } catch (BadPaddingException e) {
            e.printStackTrace();
        }
        return null;
    }

    public static void main(String[] args) {
        String deskey = "e231e93a438213bc072ffc14e80bc5b1";
        String data = "{\"name\":\"王\",\"phone\":\"13412319888\"}";
        System.out.println(encrypt(data, deskey));
    }

}
