1. 程式人生 > 其它 >Aes加解密工具類

Aes加解密工具類

public class AesUtil {
public static final String UTF_8 = "UTF-8";
/**
* 必須16位
*/
private static final String S_KEY ="0123456789ABCDEF";
    /**
* 必須16位
*/
private static final String IV_PARAMETER = "0123456789ABCDEF";
/**
* 演算法名稱
*/
private static final String KEY_ALGORITHM_AES = "AES";
/**
* 演算法/模式/填充
**/
private static final String CIPHER_MODE = "AES/CBC/PKCS5Padding";

/**
* 加密(結果為16進位制字串)
**/
public static String encrypt(String content) throws UnsupportedEncodingException,
NoSuchPaddingException,
NoSuchAlgorithmException,
InvalidAlgorithmParameterException,
InvalidKeyException,
BadPaddingException,
IllegalBlockSizeException {
if (content == null) {
return null;
}
SecretKeySpec secretKey = new SecretKeySpec(S_KEY.getBytes(UTF_8), KEY_ALGORITHM_AES);
IvParameterSpec ivParameterSpec = getIv();
Cipher cipher = Cipher.getInstance(CIPHER_MODE);
cipher.init(Cipher.ENCRYPT_MODE, secretKey, ivParameterSpec);
byte[] data = cipher.doFinal(content.getBytes(UTF_8));
String result = byte2hex(data);
return result;
}

/**
* 解密(輸出結果為字串)
**/
public static String decrypt(String content) throws UnsupportedEncodingException,
NoSuchPaddingException,
NoSuchAlgorithmException,
InvalidAlgorithmParameterException,
InvalidKeyException,
BadPaddingException,
IllegalBlockSizeException {
if (content == null) {
return null;
}
SecretKeySpec secretKey = new SecretKeySpec(S_KEY.getBytes(UTF_8), KEY_ALGORITHM_AES);
IvParameterSpec ivParameterSpec = getIv();
Cipher cipher = Cipher.getInstance(CIPHER_MODE);
cipher.init(Cipher.DECRYPT_MODE, secretKey, ivParameterSpec);

byte[] hexBytes = hex2byte(content);
byte[] data = cipher.doFinal(hexBytes);
return new String(data, UTF_8);
}

/**
* 位元組陣列轉成16進位制字串
**/
public static String byte2hex(byte[] b) { // 一個位元組的數,
StringBuffer sb = new StringBuffer(b.length * 2);
String tmp = "";
for (int n = 0; n < b.length; n++) {
// 整數轉成十六進位制表示
tmp = (Integer.toHexString(b[n] & 0XFF));
if (tmp.length() == 1) {
sb.append("0");
}
sb.append(tmp);
}
return sb.toString().toUpperCase(); // 轉成大寫
}

/**
* 將hex字串轉換成位元組陣列
**/
private static byte[] hex2byte(String inputString) {
if (inputString == null || inputString.length() < 2) {
return new byte[0];
}
inputString = inputString.toLowerCase();
int l = inputString.length() / 2;
byte[] result = new byte[l];
for (int i = 0; i < l; ++i) {
String tmp = inputString.substring(2 * i, 2 * i + 2);
result[i] = (byte) (Integer.parseInt(tmp, 16) & 0xFF);
}
return result;
}

public static IvParameterSpec getIv() throws UnsupportedEncodingException {
IvParameterSpec ivParameterSpec = new IvParameterSpec(IV_PARAMETER.getBytes("utf-8"));
// System.out.println("偏移量:"+byte2hex(ivParameterSpec.getIV()));
return ivParameterSpec;
}

}