package com.eifesun.monitor.upload.uploader;
import javax.crypto.Cipher;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;
public class AES {
public static byte[] encrypt(String text, String password) {
try {
Cipher cipher = Cipher.getInstance("AES/CBC/NoPadding");
int blockSize = cipher.getBlockSize();
// padding byte data as 16 * N length
byte[] dataBytes = text.getBytes("UTF-8");
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(password.getBytes("UTF-8"), "AES");
IvParameterSpec ivspec = new IvParameterSpec(password.getBytes("UTF-8"));
cipher.init(Cipher.ENCRYPT_MODE, keyspec, ivspec);
return cipher.doFinal(plaintext);
// return new sun.misc.BASE64Encoder().encode(encrypted);
}
catch (Exception e) {
e.printStackTrace();
return null;
}
}
public static String decrypt(byte[] encryptedBytes, String password) {
try {
Cipher cipher = Cipher.getInstance("AES/CBC/NoPadding");
SecretKeySpec keyspec = new SecretKeySpec(password.getBytes(), "AES");
IvParameterSpec ivspec = new IvParameterSpec(password.getBytes("UTF-8"));
cipher.init(Cipher.DECRYPT_MODE, keyspec, ivspec);
byte[] original = cipher.doFinal(encryptedBytes);
return new String(original, "UTF-8");
}
catch (Exception e) {
e.printStackTrace();
return null;
}
}
}