package com.goafanti.common.utils;

import javax.crypto.Cipher;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;
import org.apache.commons.codec.binary.Base64;

public class AesUtils {
	public static String encrypt(String content, String key) throws Exception {
		try {
			Cipher cipher = Cipher.getInstance("AES/CBC/NoPadding");
			int blockSize = cipher.getBlockSize();
			byte[] dataBytes = content.getBytes();
			int plaintextLength = dataBytes.length;
			if (plaintextLength % blockSize != 0) {
				plaintextLength = plaintextLength + (blockSize - (plaintextLength % blockSize));
			}
			byte[] plaintext = new byte[plaintextLength];
			System.arraycopy(dataBytes, 0, plaintext, 0, dataBytes.length);
			SecretKeySpec keyspec = new SecretKeySpec(key.getBytes(), "AES");
			IvParameterSpec ivspec = new IvParameterSpec(key.getBytes());
			cipher.init(Cipher.ENCRYPT_MODE, keyspec, ivspec);
			return Base64.encodeBase64String(cipher.doFinal(plaintext));
		} catch (Exception e) {
			e.printStackTrace();
			return null;
		}
	}

	public static String decrypt(String content, String key) throws Exception {
		try {
			byte[] decoded = Base64.decodeBase64(content);
			Cipher cipher = Cipher.getInstance("AES/CBC/NoPadding");
			SecretKeySpec keyspec = new SecretKeySpec(key.getBytes(), "AES");
			IvParameterSpec ivspec = new IvParameterSpec(key.getBytes());
			cipher.init(Cipher.DECRYPT_MODE, keyspec, ivspec);
			byte[] original = cipher.doFinal(decoded);
			int i = original.length - 1;
			for (; i >= 0; i--) {
				if (original[i] != 0) {
					break;
				}
			}
			byte[] subarray = new byte[i + 1];
			System.arraycopy(original, 0, subarray, 0, i + 1);
			return new String(subarray);
		} catch (Exception e) {
			e.printStackTrace();
			return null;
		}
	}
}