由於項目需要aes加密,所以在網上找了幾個aes加密工具。本想拿來直接用,發現都是加密後在一些在線解密網站無法解密成功(如這個網站 http://www.seacha.com/tools/aes.html),所以不得不自己寫一份,下面是能直接在在線解密網站解密成功的代碼,發出來以避免大家重複的造輪子。
package com.runmeng.sycz.util;
import javax.crypto.Cipher;
import javax.crypto.spec.SecretKeySpec;
public class AESUtil {
/**
* @param
* @return AES加密算法加密
* @throws Exception
*/
public static String encrypt(String seed, String key)
throws Exception {
byte[] result = encrypt(seed.getBytes("utf-8"), key.getBytes());
return toHex(result);
}
public static String decryptString(String src, String key) throws Exception {
byte[] input = toByte(src);
Cipher cipher = Cipher.getInstance("AES/ECB/PKCS5Padding");
SecretKeySpec securekey = new SecretKeySpec(key.getBytes(), "AES");//設置加密Key
cipher.init(Cipher.DECRYPT_MODE, securekey);//設置密鑰和解密形式
byte[] result= cipher.doFinal(input);
String resultStr=new String(result,"utf-8");
return resultStr;
}
private static byte[] encrypt(byte[] byteData, byte[] byteKey) throws Exception {
Cipher cipher = Cipher.getInstance("AES/ECB/PKCS5Padding");
SecretKeySpec skeySpec = new SecretKeySpec(byteKey, "AES");
cipher.init(Cipher.ENCRYPT_MODE, skeySpec);
byte[] decrypted = cipher.doFinal(byteData);
return decrypted;
}
private static String toHex(byte[] buf) {//字符串轉換爲16進制
final String HEX = "0123456789ABCDEF";
if (buf == null)
return "";
StringBuffer result = new StringBuffer(2 * buf.length);
for (int i = 0; i < buf.length; i++) {
result.append(HEX.charAt((buf[i] >> 4) & 0x0f)).append(
HEX.charAt(buf[i] & 0x0f));
}
return result.toString();
}
private static byte[] toByte(String hexString) {//16進制轉換爲字符串
int len = hexString.length() / 2;
byte[] result = new byte[len];
for (int i = 0; i < len; i++)
result[i] = Integer.valueOf(hexString.substring(2 * i, 2 * i + 2),
16).byteValue();
return result;
}
}