Skip to content

Instantly share code, notes, and snippets.

@nickfox
Created Feb 15, 2011
Embed
What would you like to do?
package com.mysite.aes;
import javax.crypto.*;
import javax.crypto.spec.*;
public class AES {
static String key = "Z7Y74jNe43F3o15T"; // must be 16-bytes
static String iv = "P0LrHf3nkBo7z46f";
public static String Encrypt(String stringToEncrypt) {
String stringTmp = stringToEncrypt.trim();
byte[] encrypted = null;
try {
SecretKeySpec keyspec = new SecretKeySpec(key.getBytes(), "AES");
IvParameterSpec ivspec = new IvParameterSpec(iv.getBytes("UTF8"));
Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5PADDING");
cipher.init(Cipher.ENCRYPT_MODE, keyspec, ivspec);
encrypted = cipher.doFinal(stringTmp.getBytes("UTF8"));
}catch (Exception e) {}
return bytesToHex(encrypted);
}
public static String Decrypt(String stringToDecrypt) {
String stringTmp = stringToDecrypt.trim();
byte[] outText = null;
try {
SecretKeySpec keySpec = new SecretKeySpec(key.getBytes("UTF8"), "AES");
IvParameterSpec ivSpec = new IvParameterSpec(iv.getBytes("UTF8"));
Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5PADDING");
cipher.init(Cipher.DECRYPT_MODE, keySpec, ivSpec);
outText = cipher.doFinal(hexToBytes(stringTmp));
} catch (Exception e) {}
return new String(outText).trim();
}
public static String bytesToHex(byte[] data) {
if (data==null) {
return null;
} else {
int len = data.length;
String str = "";
for (int i=0; i<len; i++) {
if ((data[i]&0xFF)<16) {
str = str + "0" + java.lang.Integer.toHexString(data[i]&0xFF);
} else {
str = str + java.lang.Integer.toHexString(data[i]&0xFF);
}
}
return str;
}
}
public static byte[] hexToBytes(String str) {
if (str==null) {
return null;
} else if (str.length() < 2) {
return null;
} else {
int len = str.length() / 2;
byte[] buffer = new byte[len];
for (int i=0; i<len; i++) {
buffer[i] = (byte) Integer.parseInt(str.substring(i*2,i*2+2),16);
}
return buffer;
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment