先码代码,后续再补上注释
/** * AES加密 * * @param sourceStr 需要加密的字符串 * @return AES加密结果为btye数组,考虑到可读性以及加密后的byte数组与String类之间强转是不可逆的。 * 因此返回结果将btye数组转换成十六进制字符串 * 加密失败后会抛出异常 */ public static String encryptAES(String srcStr, String key) { try { Cipher cipher = Cipher.getInstance("AES"); cipher.init(Cipher.ENCRYPT_MODE, getKey(key)); return parseToHexStr(cipher.doFinal(srcStr.getBytes())); } catch (Exception e) { throw Exceptions.unchecked(e); } } /** * AES解密 * * @param srcStr AES加密后提供的十六进制字符串 * @return 以项目默认编码输出解密后字符串 * 解密失败后会抛出异常 */ public static String decryptAES(String srcStr, String key) { try { byte[] srcBytes = parseToBytes(srcStr); Cipher cipher = Cipher.getInstance("AES"); cipher.init(Cipher.DECRYPT_MODE, getKey(key)); return new String(cipher.doFinal(srcBytes), Charset.defaultCharset()); } catch (Exception e) { throw Exceptions.unchecked(e); } } /** * btye数组转换成十六进制的字符串 */ private static String parseToHexStr(byte[] bytes) { StringBuilder stringBuilder = new StringBuilder(); for (byte aByte : bytes) { String hex = Integer.toHexString(aByte & 0xFF); stringBuilder.append(hex.length() == 1 ? '0' + hex : hex); } return stringBuilder.toString(); } /** * 十六进制字符串转成btye数组 */ private static byte[] parseToBytes(String src) { byte[] resBytes = new byte[src.length() / 2]; for (int i = 0; i < resBytes.length; i++) { Integer highPlace = Integer.parseInt(src.substring(i * 2, i * 2 + 1), 16); Integer lowPlace = Integer.parseInt(src.substring(i * 2 + 1, (i + 1) * 2), 16); resBytes[i] = (byte) (highPlace * 16 + lowPlace); } return resBytes; } /** * 根据给定的key生成密钥,由于windows和lunix 内部实现 SecureRandom 原理不同,在指定获取密钥方法后需要setSeed */ private static SecretKey getKey(String key) { try { KeyGenerator kegen = KeyGenerator.getInstance("AES"); SecureRandom secureRandom = SecureRandom.getInstance("SHA1PRNG"); secureRandom.setSeed(key.getBytes()); //指定密钥长度为128位 kegen.init(128, secureRandom); return kegen.generateKey(); } catch (Exception e) { throw Exceptions.unchecked(e); } }