沒有那么多廢話,我知道這是一個簡單的加密工具類沐序,但是網上的工具類很雜棺弊,我這至少保證全都是自己試驗過的可以直接使用帆啃!
/**
* AES加密工具 模式:CBC 補碼方式:PKCS5Padding
* @author Administrator
*
*/
public class AESCBCUtils {
// 加密
public static String encrypt(String sSrc, String encodingFormat, String sKey, String ivParameter) throws Exception {
Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
byte[] raw = sKey.getBytes();
SecretKeySpec skeySpec = new SecretKeySpec(raw, "AES");
IvParameterSpec iv = new IvParameterSpec(ivParameter.getBytes());// 使用CBC模式,需要一個向量iv虐秋,可增加加密算法的強度
cipher.init(Cipher.ENCRYPT_MODE, skeySpec, iv);
byte[] encrypted = cipher.doFinal(sSrc.getBytes(encodingFormat));
return parseByte2HexStr(encrypted);// 此處使用BASE64做轉碼榕茧。
}
public static String decrypt(String sSrc, String encodingFormat, String sKey, String ivParameter) throws Exception {
try {
byte[] raw = sKey.getBytes("utf-8");
SecretKeySpec skeySpec = new SecretKeySpec(raw, "AES");
Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
IvParameterSpec iv = new IvParameterSpec(ivParameter.getBytes());
cipher.init(Cipher.DECRYPT_MODE, skeySpec, iv);
byte[] encrypted1 = parseHexStr2Byte(sSrc);//先用base64解密
byte[] original = cipher.doFinal(encrypted1);
String originalString = new String(original,encodingFormat);
return originalString;
} catch (Exception ex) {
return null;
}
}
/**
* 將二進制轉換成十六進制
*
* @param buf
* @return
*/
private static String parseByte2HexStr(byte buf[]) {
StringBuffer sb = new StringBuffer();
for (int i = 0; i < buf.length; i++) {
String hex = Integer.toHexString(buf[i] & 0xFF);
if (hex.length() == 1) {
hex = '0' + hex;
}
sb.append(hex.toUpperCase());
}
return sb.toString();
}
/**
* 將十六進制轉換為二進制
*
* @param hexStr
* @return
*/
private static byte[] parseHexStr2Byte(String hexStr) {
if (hexStr.length() < 1) {
return null;
} else {
byte[] result = new byte[hexStr.length() / 2];
for (int i = 0; i < hexStr.length() / 2; i++) {
int high = Integer.parseInt(hexStr.substring(i * 2, i * 2 + 1), 16);
int low = Integer.parseInt(hexStr.substring(i * 2 + 1, i * 2 + 2), 16);
result[i] = (byte) (high * 16 + low);
}
return result;
}
}
}