package com.qmth.teachcloud.report.business.utils;

import org.apache.commons.codec.binary.Hex;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.crypto.Cipher;
import javax.crypto.NoSuchPaddingException;
import javax.crypto.spec.SecretKeySpec;
import java.security.InvalidKeyException;
import java.security.Key;
import java.security.NoSuchAlgorithmException;

/**
 * @author by xf
 * @date 2019/11/25.
 * DigestUtils.md5Hex进行md5加密
 */
public class EncrypAES {

    private static final Logger logger = LoggerFactory.getLogger(EncrypAES.class);

    private static final String KEY_ALGORITHM = "AES";
    /**
     * 加解密算法/工作模式/填充方式
     */
    private static final String DEFAULT_CIPHER_ALGORITHM = "AES/ECB/PKCS5Padding";


    private static byte[] KEYBYTES = {0x31, 0x32, 0x33, 0x34, 0x35, 0x50, 0x37, 0x38, 0x39, 0x40, 0x41, 0x42, 0x43, 0x44, 0x45, 0x46};


    /**
     * 加密
     * @param value
     * @return
     */
    public static String encrypt(String value) {
        String s = null;
        int mode = Cipher.ENCRYPT_MODE;
        try {
            Cipher cipher = initCipher(mode);
            byte[] outBytes = cipher.doFinal(value.getBytes());
            s = String.valueOf(Hex.encodeHex(outBytes));
        } catch (Exception e) {
            logger.error(e.getMessage());
        }
        return s;
    }


    /**
     * 解密
     * @param value
     * @return
     */
    public static String decrypt(String value) {
        String s = null;
        int mode = Cipher.DECRYPT_MODE;
        try {
            Cipher cipher = initCipher(mode);
            byte[] outBytes = cipher.doFinal(Hex.decodeHex(value.toCharArray()));
            s = new String(outBytes);
        } catch (Exception e) {
            logger.error(e.getMessage());
        }
        return s;
    }

    private static Cipher initCipher(int mode) throws NoSuchAlgorithmException,
            NoSuchPaddingException, InvalidKeyException {
        Cipher cipher = Cipher.getInstance(DEFAULT_CIPHER_ALGORITHM);
        Key key = new SecretKeySpec(KEYBYTES, KEY_ALGORITHM);
        cipher.init(mode, key);
        return cipher;
    }

    public static void main(String[] args) {
        String content = "12019302130225";
        String en = encrypt(content);
        System.out.println("en:" + en);

        String de = decrypt(en);
        System.out.println("de:" + de);
    }

}
