package com.sptg.estate.biz.util;

import org.springframework.util.StringUtils;
import sun.misc.BASE64Decoder;
import sun.misc.BASE64Encoder;

import javax.crypto.Cipher;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;
import java.util.Base64;

public class AESPlus {

	public static String encrypt(String strKey,String strln) throws Exception {
		if(!StringUtils.hasText(strln)){
			return null;
		}
		SecretKeySpec skeySpec = getKey(strKey);
		Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
		IvParameterSpec iv = new IvParameterSpec(strKey.getBytes());
		cipher.init(Cipher.ENCRYPT_MODE,skeySpec,iv);
		byte[] encrypted = cipher.doFinal(strln.getBytes());
		return new BASE64Encoder().encode(encrypted);
	}

	public static String decrypt(String strKey,String strln) throws Exception {
		if(!StringUtils.hasText(strln)){
			return null;
		}
		SecretKeySpec skeySpec = getKey(strKey);
		Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
		IvParameterSpec iv = new IvParameterSpec(strKey.getBytes());
		cipher.init(Cipher.DECRYPT_MODE,skeySpec,iv);
		byte[] encrypted1 = new BASE64Decoder().decodeBuffer(strln);
		byte[] original = cipher.doFinal(encrypted1);
		String originalString = new String(original);
		return originalString;
	}

	public static SecretKeySpec getKey(String strKey) throws Exception{
		byte[] arrBTmp = strKey.getBytes();
		byte[] arrB = new byte[16];

		for(int i=0;i<arrBTmp.length&&i<arrB.length;i++){
			arrB[i] = arrBTmp[i];
		}
		SecretKeySpec skeySpec = new SecretKeySpec(arrB,"AES");
		return skeySpec;
	}

	public static void main(String[] args) throws Exception{
		String key = "123456789ABCDEFG";
		String content = "{\"status\":1,\"parkCode\": \"6651216\",\"armCode\": \"2002\",\"parkName\": \"天亮停车场\",\"vplNumber\":\"dsdfasf\",\"recordId\": 352,\"inTime\": 15102271751,\"vplType\":0,\"carType\":0,\"vplColor\":0,\"image\": \"http://l\"}";

		String jiami =AESPlus.encrypt(key,content);
		String utfJiami= Base64.getEncoder().encodeToString(jiami.getBytes());
		System.out.println(utfJiami);
//
//		String jiemi = Base64.getDecoder().decode(utfJiami.getBytes()).toString();

		String decrypt = AESPlus.decrypt(key, jiami);


		System.out.println(decrypt);


	}
}
