package com.hx.util; import org.apache.commons.codec.binary.Base64; import javax.crypto.Cipher; import javax.crypto.SecretKey; import javax.crypto.spec.SecretKeySpec; import java.io.UnsupportedEncodingException; /** * AES加密工具类 */ public class Aes { /** * 将二进制转换成16进制 * * @param buf 字节数组 * @return */ public 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(); } /** * 将16进制转换为二进制 * * @param hexStr 16进制字符 * @return */ public static byte[] parseHexStr2Byte(String hexStr) { if (hexStr.length() < 1) return null; 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; } /** * 加密 * @param str 待加密字符串 * @param secret 密钥 * @return */ public static byte[] encrypt(String str, String secret) { if (null != str) { byte[] bytes = null; try { Base64 base64 = new Base64(); String ALGORITHM = "AES"; SecretKey desKey = new SecretKeySpec(secret.getBytes("UTF-8"), ALGORITHM);// 生成密钥 Cipher c; c = Cipher.getInstance(ALGORITHM); c.init(Cipher.ENCRYPT_MODE, desKey); bytes = c.doFinal(str.getBytes("UTF-8")); return bytes; } catch (Exception e) { e.printStackTrace(); } } return null; } /** * 解密 * @param str 待解密字符串 * @param secret 密钥 * @return */ public static byte[] decrypt(byte[] str, String secret) { try { String ALGORITHM = "AES"; SecretKey desKey = new SecretKeySpec(secret.getBytes("UTF-8"), ALGORITHM);// 生成密钥 Cipher c = Cipher.getInstance(ALGORITHM); c.init(Cipher.DECRYPT_MODE, desKey); return c.doFinal(str); } catch (Exception e) { e.printStackTrace(); } return null; } public static void main(String[] args) throws UnsupportedEncodingException { String content = "apiKey=phitabfaceapi&userId=o5W1it6Pvqn6vPX6E1BGERH8J1lw"; String password = "phitabfacesecret"; byte[] encode = encrypt(content, password); String code = parseByte2HexStr(encode); System.out.println("密文字符串:" + code); //16进制字符串转成字节数组 byte[] decode = parseHexStr2Byte(code); // 解密 byte[] decryptResult = decrypt(decode, password); System.out.println("解密后:" + new String(decryptResult, "UTF-8")); //不转码会乱码 } }