package com.zcxk.core.utils.encrypt;

import java.security.InvalidAlgorithmParameterException;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import java.security.spec.AlgorithmParameterSpec;
import java.security.spec.InvalidKeySpecException;
import java.security.spec.KeySpec;
import javax.crypto.Cipher;
import javax.crypto.NoSuchPaddingException;
import javax.crypto.SecretKey;
import javax.crypto.SecretKeyFactory;
import javax.crypto.spec.PBEKeySpec;
import javax.crypto.spec.PBEParameterSpec;
import org.apache.commons.codec.binary.Hex;
/**
 * @author Andy
 * @description: DesCrypto
 * @date 2021/7/16
 * @version V1.0
 **/
public class DesCrypto {
    private static final String PASSWORD = "i1swgovpn9wh";

    /**
     *  8-byte Salt
     */
    private static final byte[] SALT = { (byte) 0xa9, (byte) 0x9a, (byte) 0xb8, (byte) 0x32,
            (byte) 0x59, (byte) 0x45, (byte) 0xc3, (byte) 0x13 };

    /**
     * Iteration count
     */
    private static final int ITERATION_COUNT = 15;

    private static Cipher getCipher(int mod, String password) throws InvalidKeySpecException,
            NoSuchAlgorithmException, NoSuchPaddingException, InvalidKeyException,
            InvalidAlgorithmParameterException {
        KeySpec keySpec = new PBEKeySpec(password.toCharArray(), SALT, ITERATION_COUNT);
        SecretKey key = SecretKeyFactory.getInstance("PBEWithMD5AndDES").generateSecret(keySpec);
        // Prepare the parameter to the ciphers
        AlgorithmParameterSpec paramSpec = new PBEParameterSpec(SALT, ITERATION_COUNT);
        Cipher cipher = Cipher.getInstance(key.getAlgorithm());
        cipher.init(mod, key, paramSpec);
        return cipher;
    }

    /**
     * 对称加密
     * @param str
     * @return
     */
    public static String encrypt(String str) {
        try {
            byte[] utf8 = str.getBytes("UTF-8");
            byte[] enc = getCipher(Cipher.ENCRYPT_MODE, PASSWORD).doFinal(utf8);
            return new String(Hex.encodeHex(enc));
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * 解密
     * @param str
     * @return
     */
    public static String decrypt(String str) {
        try {
            byte[] dec = Hex.decodeHex(str.toCharArray());
            byte[] utf8 = getCipher(Cipher.DECRYPT_MODE, PASSWORD).doFinal(dec);
            return new String(utf8, "UTF-8");
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }
}
