package com.xhpc.evcs.encryption;

import javax.crypto.*;
import javax.crypto.spec.SecretKeySpec;
import java.io.UnsupportedEncodingException;
import java.nio.charset.StandardCharsets;
import java.security.InvalidAlgorithmParameterException;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import java.util.Arrays;
import java.util.Base64;

public class Aes128Cbc {

    private static int AES_128 = 128;

    public static String encrypt(String msg, String dataSecret, String dataSecretIV) throws NoSuchAlgorithmException,
            IllegalBlockSizeException, InvalidKeyException, BadPaddingException,
            InvalidAlgorithmParameterException, NoSuchPaddingException {

        KeyGenerator keyGenerator = KeyGenerator.getInstance(CryptoMngr.ALGORITHM);
        keyGenerator.init(AES_128);
        byte[] ds = (dataSecret).getBytes(StandardCharsets.UTF_8);
        ds = Arrays.copyOf(ds, 16);
        SecretKey key = new SecretKeySpec(ds, "AES");
        byte[] dsiv = (dataSecretIV).getBytes(StandardCharsets.UTF_8);
        dsiv = Arrays.copyOf(dsiv, 16);
        SecretKey IV = new SecretKeySpec(dsiv, "AES");
        byte[] cipherText = CryptoMngr.encrypt(key.getEncoded(), IV.getEncoded(), msg.getBytes());
        return Base64.getEncoder().encodeToString(cipherText);
    }

    public static byte[] decryptBytes(String encryptedMsg, String dataSecret, String dataSecretIV) throws NoSuchAlgorithmException, IllegalBlockSizeException, InvalidKeyException, BadPaddingException, InvalidAlgorithmParameterException, NoSuchPaddingException {

        if (encryptedMsg.startsWith("{") || encryptedMsg.startsWith("[")) {
            throw new IllegalArgumentException("不是合法的加密字符串");
        }
        KeyGenerator keyGenerator = KeyGenerator.getInstance(CryptoMngr.ALGORITHM);
        keyGenerator.init(AES_128);
        byte[] ds = (dataSecret).getBytes(StandardCharsets.UTF_8);
        ds = Arrays.copyOf(ds, 16);
        SecretKey key = new SecretKeySpec(ds, "AES");
        byte[] dsiv = (dataSecretIV).getBytes(StandardCharsets.UTF_8);
        dsiv = Arrays.copyOf(dsiv, 16);
        SecretKey IV = new SecretKeySpec(dsiv, "AES");
        byte[] cipherText = Base64.getDecoder().decode(encryptedMsg.getBytes());
        byte[] decryptedBytes = CryptoMngr.decrypt(key.getEncoded(), IV.getEncoded(), cipherText);
        return decryptedBytes;
    }

    public static String decryptString(String encryptedMsg, String dataSecret, String dataSecretIV) throws NoSuchAlgorithmException,
            IllegalBlockSizeException, InvalidKeyException, BadPaddingException,
            InvalidAlgorithmParameterException, NoSuchPaddingException {

        if (encryptedMsg == null || encryptedMsg.length() == 0) return "";
        byte[] decryptedBytes = decryptBytes(encryptedMsg, dataSecret, dataSecretIV);
        return new String(decryptedBytes);
    }

    public static void main(String[] args) throws BadPaddingException, InvalidAlgorithmParameterException,
            NoSuchAlgorithmException, IllegalBlockSizeException, UnsupportedEncodingException, NoSuchPaddingException,
            InvalidKeyException {

        System.out.println(decryptString("vTGCo/ntYzY9ZLHnATipTR1WHP4hHjsB5byV2g62bxbNVQkGba8+u07Dv95vihuO+zYV" +
                        "/+9qwTUaSvFGUm0M1T9VMThVlsarbCMsBCgC2KE=",
                "ojs67l46z3f7rhok", "tet9swfkyojkhaos"
        ));
        //ujNoGsWRo5MyPKYOxeofKwgPEng3xF+yhM8DDjwtwHo=
        System.out.println(encrypt("{\"StationIDs\":[\"1\"]}", "8LpncubmWiPCzY3V", "av6A8QdnRaVRMXu6"));
        System.out.println(encrypt("{\"OperatorID\":\"MA5FNJXW9\", \"OperatorSecret\":\"Ut5UFdqDthiJyncU\"}",
                "8LpncubmWiPCzY3V", "av6A8QdnRaVRMXu6"));
    }
}
