package com.seeyon.apps.src_hxinvoice.util;

import lombok.extern.slf4j.Slf4j;

import javax.crypto.Cipher;
import javax.crypto.SecretKey;
import javax.crypto.spec.SecretKeySpec;
import java.nio.charset.StandardCharsets;

/**
 * 3DES加解密工具类
 *
 * @author ZSC-DXHY
 * @date 创建时间: 2020-08-14 15:45
 */
@Slf4j
public class TripleDesUtil {
    private static final String LOGGER_MSG = "(3DES解密)";

    /**
     * 定义 加密算法,可用 DES,DESede,Blowfish
     */
    private static final String ALGORITHM = "DESede";

    /**
     * 加密算法
     * password为加密密钥，长度24字节
     * src为被加密的数据缓冲区
     */
    public static byte[] encryptMode(String password, byte[] src) {
        try {
            //生成密钥
            SecretKey deskey = new SecretKeySpec(password.getBytes(StandardCharsets.UTF_8), ALGORITHM);
            //加密
            Cipher c1 = Cipher.getInstance(ALGORITHM);
            c1.init(Cipher.ENCRYPT_MODE, deskey);
            return c1.doFinal(src);
        } catch (Exception e1) {
//            log.error("{}3DES加密异常:{}", LOGGER_MSG, e1);
            System.out.println("{}3DES加密异常:{}"+e1 );
        }
        return null;
    }


    /**
     * 解密算法
     * password为解密密钥，长度24字节
     * src为被加密的数据缓冲区
     */
    public static byte[] decryptMode(String password, byte[] src) {
        try {
            //生成密钥
            SecretKey deskey = new SecretKeySpec(password.getBytes(StandardCharsets.UTF_8), ALGORITHM);
            //解密
            Cipher c1 = Cipher.getInstance(ALGORITHM);
            c1.init(Cipher.DECRYPT_MODE, deskey);
            return c1.doFinal(src);
        } catch (Exception e2) {
//            log.error("{}3DES解密异常:{}", LOGGER_MSG, e2);
            System.out.println("{}3DES解密异常:{}"+e2);
        }
        return null;
    }

}
