package Crypter;
import java.security.MessageDigest;
import java.security.spec.AlgorithmParameterSpec;
import java.util.Arrays;
import javax.crypto.Cipher;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;
import sun.misc.BASE64Decoder;
public class AEScrypter {
Cipher ecipher;
Cipher dcipher;
byte[] iv = new byte[] { 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07,
0x08, 0x09, 0x0a, 0x0b, 0x0c, 0x0d, 0x0e, 0x0f };
public AEScrypter(String password) {
try {
BASE64Decoder b64 = new BASE64Decoder();
byte[] cipherText = b64.decodeBuffer(password);
MessageDigest messagedigest = MessageDigest.getInstance("MD5");
messagedigest.reset();
messagedigest.update(cipherText);
Arrays.fill(cipherText, (byte) 0);
SecretKeySpec skeySpec = new SecretKeySpec(messagedigest.digest(),"AES");
AlgorithmParameterSpec paramSpec = new IvParameterSpec(iv);
ecipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
dcipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
ecipher.init(Cipher.ENCRYPT_MODE, skeySpec, paramSpec);
dcipher.init(Cipher.DECRYPT_MODE, skeySpec, paramSpec);
} catch (Exception e) {
System.err.println(e);
}
}
public String StringToAES(String str){
try {
byte[] utf8 = str.getBytes("UTF8");
byte[] enc = ecipher.doFinal(utf8);
str = new sun.misc.BASE64Encoder().encode(enc);
str = str.replace("\n", "");
str = str.replace("\r", "");
} catch (Exception e) {
System.err.println(e);
}
return str;
}
public byte[] encrypt(byte[] bytes) {
byte[] enc = null;
try {
enc = ecipher.doFinal(bytes);
} catch (Exception e) {
System.err.println(e);
}
return enc;
}
public byte[] decrypt(byte[] bytes) {
byte[] dec = null;
try {
dec = dcipher.doFinal(bytes);
} catch (Exception e) {
System.err.println(e);
}
return dec;
}
public String AEStoString(String str) {
try {
byte[] dec = new sun.misc.BASE64Decoder().decodeBuffer(str);
byte[] utf8 = dcipher.doFinal(dec);
return new String(utf8, "UTF8");
} catch (Exception e) {
System.err.println(e);
}
return str;
}
/*
public static void main(String[] args) {
AEScrypter aesCrypter = new AEScrypter("myPassword");
String str = "dayaftereh";
str = aesCrypter.StringToAES(str);
System.out.println("en: "+str);
System.out.println("de: "+aesCrypter.AEStoString(str));
}
*/
}