public class EncryptUtil {
// --------------------部分代碼-----------
/**
* AES加密
*
* @param key
* 密鑰信息
* @param content
* 待加密信息
*/
public static byte[] encodeAES(byte[] key, byte[] content) throws Exception {
// 不是16的倍數的,補足
int base = 16;
if (key.length % base != 0) {
int groups = key.length / base + (key.length % base != 0 ? 1 : 0);
byte[] temp = new byte[groups * base];
Arrays.fill(temp, (byte) 0);
System.arraycopy(key, 0, temp, 0, key.length);
key = temp;
}
SecretKey secretKey = new SecretKeySpec(key, "AES");
IvParameterSpec iv = new IvParameterSpec(new byte[] { 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0 });
Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
cipher.init(Cipher.ENCRYPT_MODE, secretKey, iv);
byte[] tgtBytes = cipher.doFinal(content);
return tgtBytes;
}
/**
* AES解密
*
* @param key
* 密鑰信息
* @param content
* 待加密信息
* @return
* @throws Exception
*/
public static byte[] decodeAES(byte[] key, byte[] content) throws Exception {
// 不是16的倍數的,補足
int base = 16;
if (key.length % base != 0) {
int groups = key.length / base + (key.length % base != 0 ? 1 : 0);
byte[] temp = new byte[groups * base];
Arrays.fill(temp, (byte) 0);
System.arraycopy(key, 0, temp, 0, key.length);
key = temp;
}
SecretKey secretKey = new SecretKeySpec(key, "AES");
IvParameterSpec iv = new IvParameterSpec(new byte[] { 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0 });
Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
cipher.init(Cipher.DECRYPT_MODE, secretKey, iv);
byte[] tgtBytes = cipher.doFinal(content);
return tgtBytes;
}
//身份驗證使用這個方法。
public static String encryptAES(String content, String key) {
try {
return bytesToHexString(encodeAES(key.getBytes(),
content.getBytes()));
} catch (Exception e) {
return null;
}
}
public static String decryptAES(String content, String key) {
try {
byte[] contentByte = hexStringToByte(content);
return new String(decodeAES(key.getBytes(), contentByte),
"UTF-8");
} catch (Exception e) {
return null;
}
}
/**
* 把字節數組轉換成16進制字符串
*
* @parambArray
* @return
*/
public static String bytesToHexString(byte[] bArray) {
StringBuffer sb = new StringBuffer(bArray.length);
String sTemp;
for (int i = 0; i<bArray.length; i++) {
sTemp = Integer.toHexString(0xFF &bArray[i]);
if (sTemp.length() < 2)
sb.append(0);
sb.append(sTemp.toUpperCase());
}
return sb.toString();
}
/*
* 把16進制字符串轉換成字節數組
*
* @param hex
*
* @return
*/
public static byte[] hexStringToByte(String hex) {
int len = (hex.length() / 2);
byte[] result = new byte[len];
char[] achar = hex.toCharArray();
for (int i = 0; i<len; i++) {
int pos = i * 2;
result[i] = (byte) (toByte(achar[pos]) << 4 | toByte(achar[pos + 1]));
}
return result;
}
private static byte toByte(char c) {
byte b = (byte) "0123456789ABCDEF".indexOf(c);
return b;
}
}