package jj.tech.paolu.utils;


import org.apache.commons.codec.binary.Base64;
import org.apache.commons.codec.digest.DigestUtils;

import javax.crypto.Cipher;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;
import java.nio.charset.Charset;

public class AES {

	private Cipher CBC;
	private Cipher ECB;
	private IvParameterSpec ivParameterSpec;
	private SecretKeySpec secretKeySpec;

	public AES(){
		this("ssdkF$HUy2A#D%kd","weJiSEvR5yAC5ftB");
	}
	public AES(String KEY, String IV){
		try {
	    	this.CBC = Cipher.getInstance("AES/CBC/PKCS5PADDING");
	    	this.ECB = Cipher.getInstance("AES/ECB/PKCS5PADDING");
	    	this.ivParameterSpec = new IvParameterSpec(IV.getBytes(Charset.defaultCharset()));
	    	this.secretKeySpec = new SecretKeySpec(KEY.getBytes(Charset.defaultCharset()), "AES");
	    } catch (Exception e) {
			e.printStackTrace();
		}
	}



	public String encryptCBC(String toBeEncrypt){
		try {
			CBC.init(Cipher.ENCRYPT_MODE, secretKeySpec, ivParameterSpec);
		    byte[] encrypted = CBC.doFinal(toBeEncrypt.getBytes());
		    return Base64.encodeBase64URLSafeString(encrypted);
		}catch(Exception e) {
			e.printStackTrace();
			return null;
		}
	}


	public String decryptCBC(String encrypted){
		try {
			CBC.init(Cipher.DECRYPT_MODE, secretKeySpec, ivParameterSpec);
		    byte[] decryptedBytes = CBC.doFinal(Base64.decodeBase64(encrypted));
		    return new String(decryptedBytes);
		}catch(Exception e) {
			e.printStackTrace();
			return null;
		}
	}

	public String encrypt(String toBeEncrypt){
		try {
			ECB.init(Cipher.ENCRYPT_MODE, secretKeySpec);
		    byte[] encrypted = ECB.doFinal(toBeEncrypt.getBytes());
		    return Base64.encodeBase64URLSafeString(encrypted);
		}catch(Exception e) {
			e.printStackTrace();
			return null;
		}
	}
	public String decrypt(String encrypted){
		try {
			ECB.init(Cipher.DECRYPT_MODE, secretKeySpec);
		    byte[] decryptedBytes = ECB.doFinal(Base64.decodeBase64(encrypted));
		    return new String(decryptedBytes);
		}catch(Exception e) {
			e.printStackTrace();
			return null;
		}
	}

	public static void main(String[] args) {
		AES a = new AES();
		String s = a.encryptCBC("111");
		String v = a.decryptCBC(s);
		System.out.println(s);
		System.out.println(v);


		String bb = a.encrypt("222");
		String cc = a.decrypt(bb);
		System.out.println(bb);
		System.out.println(cc);


		String m = DigestUtils.sha3_256Hex("000000");
		System.out.println("sha3256:"+m);
		

		System.out.println(a.encrypt("555555555551"));
		System.out.println(a.decrypt(a.encrypt("555555555551")));

	}

}
