沒有那么多廢話捻脖,我知道這是一個簡單的加密工具類上鞠,但是網(wǎng)上的工具類很雜尺借,我這至少保證全都是自己試驗過的可以直接使用!
/**
* AES加密工具 模式:ECB 補碼方式:PKCS5Padding
* @author Administrator
*
*/
public class AESUtils {
private static Logger log = LoggerFactory.getLogger(AESUtils.class);
private static String Algorithm = "AES";
private static String AlgorithmProvider = "AES/ECB/PKCS5Padding"; // 算法/模式/補碼方式
/**
* 得到轉(zhuǎn)換為16進制字符串的加密字符串
* @param src
* @param key 必須為16個字符(1234567887654321)
* @return
* @throws InvalidKeyException
* @throws NoSuchAlgorithmException
* @throws NoSuchPaddingException
* @throws IllegalBlockSizeException
* @throws BadPaddingException
* @throws UnsupportedEncodingException
* @throws InvalidAlgorithmParameterException
*/
public static String getHexStr(String src, byte[] key)
throws InvalidKeyException, NoSuchAlgorithmException, NoSuchPaddingException, IllegalBlockSizeException,
BadPaddingException, UnsupportedEncodingException, InvalidAlgorithmParameterException {
return parseByte2HexStr(encrypt(src, key));
}
/**
* 轉(zhuǎn)換16進制加密字符串變?yōu)槲醇用茏址? * @param src
* @param key
* @return
* @throws Exception
*/
public static String getSrcStr(String src, byte[] key) throws Exception {
return new String(decrypt(src, key), "utf-8");
}
public static byte[] encrypt(String src, byte[] key)
throws NoSuchAlgorithmException, NoSuchPaddingException, InvalidKeyException, IllegalBlockSizeException,
BadPaddingException, UnsupportedEncodingException, InvalidAlgorithmParameterException {
SecretKey secretKey = new SecretKeySpec(key, Algorithm);
// IvParameterSpec ivParameterSpec = getIv();
Cipher cipher = Cipher.getInstance(AlgorithmProvider);
cipher.init(Cipher.ENCRYPT_MODE, secretKey);
byte[] cipherBytes = cipher.doFinal(src.getBytes(Charset.forName("utf-8")));
return cipherBytes;
}
public static byte[] decrypt(String src, byte[] key) throws Exception {
SecretKey secretKey = new SecretKeySpec(key, Algorithm);
// IvParameterSpec ivParameterSpec = getIv();
Cipher cipher = Cipher.getInstance(AlgorithmProvider);
cipher.init(Cipher.DECRYPT_MODE, secretKey);
byte[] hexBytes = parseHexStr2Byte(src);
byte[] plainBytes = cipher.doFinal(hexBytes);
return plainBytes;
}
/**
* 將二進制轉(zhuǎn)換成十六進制
*
* @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();
}
/**
* 將十六進制轉(zhuǎn)換為二進制
*
* @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;
}
}
}