package com.cowr.common.utils; import javax.crypto.Cipher; import javax.crypto.spec.IvParameterSpec; import javax.crypto.spec.SecretKeySpec; import java.io.UnsupportedEncodingException; import java.security.GeneralSecurityException; import java.util.Arrays; public class AESUtil { public static byte[] encrypt(String key, byte[] origData) throws GeneralSecurityException { byte[] keyBytes = getKeyBytes(key); byte[] buf = new byte[16]; System.arraycopy(keyBytes, 0, buf, 0, keyBytes.length > buf.length ? keyBytes.length : buf.length); Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding"); cipher.init(Cipher.ENCRYPT_MODE, new SecretKeySpec(buf, "AES"), new IvParameterSpec(keyBytes)); return cipher.doFinal(origData); } public static byte[] decrypt(String key, byte[] crypted) throws GeneralSecurityException { byte[] keyBytes = getKeyBytes(key); byte[] buf = new byte[16]; System.arraycopy(keyBytes, 0, buf, 0, keyBytes.length > buf.length ? keyBytes.length : buf.length); Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding"); cipher.init(Cipher.DECRYPT_MODE, new SecretKeySpec(buf, "AES"), new IvParameterSpec(keyBytes)); return cipher.doFinal(crypted); } private static byte[] getKeyBytes(String key) { byte[] bytes = key.getBytes(); return bytes.length == 16 ? bytes : Arrays.copyOf(bytes, 16); } public static String encrypt(String key, String val) throws GeneralSecurityException { byte[] origData = val.getBytes(); byte[] crypted = encrypt(key, origData); return parseByte2HexStr(crypted); } public static String decrypt(String key, String val) throws GeneralSecurityException, UnsupportedEncodingException { byte[] crypted = parseHexStr2Byte(val); byte[] origData = decrypt(key, crypted); return new String(origData, "utf-8"); } /** * 将二进制转换成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 * @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; } public static void main(String[] args) throws Exception { String content = "加密之前加密之前加密之前"; String password = "21"; System.out.println("加密之前:" + content); String hexStrResult = encrypt(password, content); System.out.println("加密之后:" + hexStrResult); System.out.println("解密后的内容:" + decrypt(password, hexStrResult)); } }