package com.games.gateway.utils;

import org.apache.commons.codec.binary.Base64;
import org.bouncycastle.jce.provider.BouncyCastleProvider;

import javax.crypto.Cipher;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;
import javax.validation.constraints.NotNull;
import java.security.Security;
import java.security.spec.AlgorithmParameterSpec;

public final class AesEncodeUtil {

    //偏移量
    public static final String VIPARA = "dFd8s4fDfV6d2fsD";

    //编码方式
    private static final String CHARSET_NAME = "UTF-8";

    private static final String AES_NAME = "AES";
    //填充类型
    public static final String ALGORITHM = "AES/CBC/PKCS7Padding";

    static {
        Security.addProvider(new BouncyCastleProvider());
    }

    public static String genKey(String key) {
        return Md5.encode(key).toUpperCase();
    }

    /**
     * 加密
     *
     * @param content
     * @param key
     * @return
     */
    public static String encrypt(@NotNull String content, @NotNull String key) throws Exception {
        byte[] result = null;
        Cipher cipher = Cipher.getInstance(ALGORITHM);
        SecretKeySpec keySpec = new SecretKeySpec(key.getBytes(CHARSET_NAME), AES_NAME);
        AlgorithmParameterSpec paramSpec = new IvParameterSpec(VIPARA.getBytes());
        cipher.init(Cipher.ENCRYPT_MODE, keySpec, paramSpec);
        result = cipher.doFinal(content.getBytes(CHARSET_NAME));
        return Base64.encodeBase64String(result);
    }

    /**
     * 解密
     *
     * @param content
     * @param key
     * @return
     */
    public static String decrypt(@NotNull String content, @NotNull String key) throws Exception {
        Cipher cipher = Cipher.getInstance(ALGORITHM);
        SecretKeySpec keySpec = new SecretKeySpec(key.getBytes(CHARSET_NAME), AES_NAME);
        AlgorithmParameterSpec paramSpec = new IvParameterSpec(VIPARA.getBytes());
        cipher.init(Cipher.DECRYPT_MODE, keySpec, paramSpec);
        return new String(cipher.doFinal(Base64.decodeBase64(content)), CHARSET_NAME);
    }
}