public class AESEncryptUtil { /** * 密钥(密钥必须是16位) */ private static final String KEY = "WOSHIZHENDELIHAI"; /** * 算法 */ private static final String ALGORITHM = "AES/ECB/PKCS5Padding"; private AESEncryptUtil() {} /** * 加密 * * @param content * @return */ private static byte[] encrypt(byte[] content) { byte[] str = null; try { Cipher cipher = Cipher.getInstance(ALGORITHM); cipher.init(Cipher.ENCRYPT_MODE, new SecretKeySpec(KEY.getBytes(), "AES")); str = cipher.doFinal(content); } catch (Exception e) { log.error("加密异常{}",e.getMessage()); } return str; } /** * 解密 * * @param bytes * @return */ private static byte[] decrypt(byte[] bytes) { byte[] decryptStr = null; try { Cipher cipher = Cipher.getInstance(ALGORITHM); cipher.init(Cipher.DECRYPT_MODE, new SecretKeySpec(KEY.getBytes(), "AES")); decryptStr = cipher.doFinal(bytes); } catch (Exception e) { log.error("解密异常{}",e.getMessage()); } return decryptStr; } /** * 文件加密 * * @param file */ public static void encryptFile(File file) { try { // 以 byte 的形式读取,不改变文件数据的编码格式 byte[] bytes = Files.readAllBytes(file.toPath()); // 加密 byte[] encrypt = encrypt(bytes); // 覆盖写入文件 Files.write(file.toPath(), encrypt); } catch (Exception e) { log.error("加密异常{}",e.getMessage()); } } /** * 文件解密 * * @param file */ public static void decryptFile(File file) { try { // 以 byte 的形式读取,不改变文件数据的编码格式 byte[] bytes = Files.readAllBytes(file.toPath()); // 解密 byte[] decrypt = decrypt(bytes); // 覆盖写入文件 Files.write(file.toPath(), decrypt); } catch (Exception e) { log.error("加密异常{}",e.getMessage()); } }
AES文件加解密
于 2022-05-13 16:34:48 首次发布