package com.sdtool.common.tool;

import com.dySweetFishPlugin.tool.crypto.encoder.BASE64Decoder;
import com.dySweetFishPlugin.tool.crypto.encoder.BASE64Encoder;

import javax.crypto.Cipher;
import javax.crypto.SecretKey;
import javax.crypto.SecretKeyFactory;
import javax.crypto.spec.PBEKeySpec;
import javax.crypto.spec.SecretKeySpec;
import java.security.spec.KeySpec;

/**
 * Created by jlutt on 2018-03-09.
 *
 * @author jlutt
 */
public class AESEncrypter {

    private static final byte[] SALT = {
            (byte) 0xA9, (byte) 0x9B, (byte) 0xC8, (byte) 0x32,
            (byte) 0x56, (byte) 0x35, (byte) 0xE3, (byte) 0x03
    };
    private static final int ITERATION_COUNT = 65536;
    private static final int KEY_LENGTH = 256;
    private Cipher ecipher;
    private Cipher dcipher;

    public AESEncrypter(String passPhrase) throws Exception {

        SecretKeyFactory factory = SecretKeyFactory.getInstance("PBKDF2WithHmacSHA1");
        KeySpec spec = new PBEKeySpec(passPhrase.toCharArray(), SALT, ITERATION_COUNT, KEY_LENGTH);
        SecretKey tmp = factory.generateSecret(spec);
        SecretKey secret = new SecretKeySpec(tmp.getEncoded(), "AES");

        //ecipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
        ecipher = Cipher.getInstance("AES");
        ecipher.init(Cipher.ENCRYPT_MODE, secret);
//    ecipher.init(Cipher.ENCRYPT_MODE, secretKey);

        dcipher = Cipher.getInstance("AES");
        dcipher.init(Cipher.DECRYPT_MODE, secret);
    }

    public static void main(String[] args) throws Exception {

        String message = "{\"supplierCode\":1000,\"dataSourceId\":\"erp001\",\"id\":1,\"deptId\":0,\"userName\":\"后台管理员\",\"account\":\"admin\",\"expireTime\":1606183725572,\"userFrom\":0}\n";
        String password = "dnyERP@Token_LogiN";

        AESEncrypter encrypter = new AESEncrypter(password);
        String encrypted = encrypter.encrypt(message);
        String decrypted = encrypter.decrypt(encrypted);

        System.out.println("Encrypt(\"" + message + "\", \"" + password + "\") = \"" + encrypted + "\"");
        System.out.println("Decrypt(\"" + encrypted + "\", \"" + password + "\") = \"" + decrypted + "\"");
    }

    public String encrypt(String encrypt) throws Exception {
        byte[] bytes = encrypt.getBytes("UTF8");
        byte[] encrypted = encrypt(bytes);
        return new BASE64Encoder().encode(encrypted);
    }

    public byte[] encrypt(byte[] plain) throws Exception {
        return ecipher.doFinal(plain);
    }

    public String decrypt(String encrypt) throws Exception {
        byte[] bytes = new BASE64Decoder().decodeBuffer(encrypt);
        byte[] decrypted = decrypt(bytes);
        return new String(decrypted, "UTF8");
    }

    public byte[] decrypt(byte[] encrypt) throws Exception {
        return dcipher.doFinal(encrypt);
    }
}
