一、功能概述
开发一个基于 Java 的命令行工具,利用 AES(Advanced Encryption Standard)对称加密算法,实现对指定目录下文件的批量加密与解密操作。支持设置加密密钥,可用于保护文件内容隐私,如敏感文档、配置文件等场景,防止非授权访问。
二、技术选型与依赖
(一)语言与核心库
使用 Java 语言开发,依托 JDK 自带的 javax.crypto
包实现 AES 加密功能,无需额外引入第三方依赖,降低项目复杂度与部署成本 。
(二)加密算法说明
AES 是一种广泛应用的对称加密算法,采用分组密码体制,支持 128 位、192 位、256 位密钥长度(需注意,256 位密钥在部分环境可能需要安装 JCE Unlimited Strength Jurisdiction Policy 文件 )。本工具默认使用 128 位密钥,通过 SecretKeySpec
生成密钥,Cipher
类完成加密和解密操作 。
三、代码实现
(一)核心工具类 FileEncryptor.java
import javax.crypto.Cipher;
import javax.crypto.SecretKey;
import javax.crypto.SecretKeyFactory;
import javax.crypto.spec.DESKeySpec;
import javax.crypto.spec.SecretKeySpec;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.security.SecureRandom;
import java.util.Base64;
public class FileEncryptor {
private static final String AES_ALGORITHM = "AES";
private static final String TRANSFORMATION = "AES/ECB/PKCS5Padding";
// 生成 AES 密钥(示例为 128 位密钥,可扩展支持其他长度)
public static SecretKey generateAESKey() throws Exception {
byte[] keyBytes = new byte[16];
SecureRandom random = new SecureRandom();
random.nextBytes(keyBytes);
return new SecretKeySpec(keyBytes, AES_ALGORITHM);
}
// 加密文件
public static void encryptFile(File inputFile, File outputFile, SecretKey secretKey) throws Exception {
Cipher cipher = Cipher.getInstance(TRANSFORMATION);
cipher.init(Cipher.ENCRYPT_MODE, secretKey);
try (FileInputStream fis = new FileInputStream(inputFile);
FileOutputStream fos = new FileOutputStream(outputFile);
javax.crypto.CipherOutputStream cos = new javax.crypto.CipherOutputStream(fos, cipher)) {
byte[] buffer = new byte[1024];
int len;
while ((len = fis.read(buffer)) != -1) {
cos.write(buffer, 0, len);
}
}
}
// 解密文件
public static void decryptFile(File inputFile, File outputFile, SecretKey secretKey) throws Exception {
Cipher cipher = Cipher.getInstance(TRANSFORMATION);
cipher.init(Cipher.DECRYPT_MODE, secretKey);
try (FileInputStream fis = new FileInputStream(inputFile);
FileOutputStream fos = new FileOutputStream(outputFile);
javax.crypto.CipherInputStream cis = new javax.crypto.CipherInputStream(fis, cipher)) {
byte[] buffer = new byte[1024];
int len;
while ((len = cis.read(buffer)) != -1) {
fos.write(buffer, 0, len);
}
}
}
// 批量加密目录下文件
public static void encryptDirectory(File inputDir, File outputDir, SecretKey secretKey) throws Exception {
if (!outputDir.exists()) {
outputDir.mkdirs();
}
File[] files = inputDir.listFiles();
if (files == null) return;
for (File file : files) {
if (file.isFile()) {
File outputFile = new File(outputDir, file.getName() + ".enc");
encryptFile(file, outputFile, secretKey);
} else if (file.isDirectory()) {
File subOutputDir = new File(outputDir, file.getName());
encryptDirectory(file, subOutputDir, secretKey);
}
}
}
// 批量解密目录下文件(需对应加密后的 .enc 文件)
public static void decryptDirectory(File inputDir, File outputDir, SecretKey secretKey) throws Exception {
if (!outputDir.exists()) {
outputDir.mkdirs();
}
File[] files = inputDir.listFiles();
if (files == null) return;
for (File file : files) {
if (file.isFile() && file.getName().endsWith(".enc")) {
String originalName = file.getName().substring(0, file.getName().length() - 4);
File outputFile = new File(outputDir, originalName);
decryptFile(file, outputFile, secretKey);
} else if (file.isDirectory()) {
File subOutputDir = new File(outputDir, file.getName());
decryptDirectory(file, subOutputDir, secretKey);
}
}
}
public static void main(String[] args) {
try {
SecretKey secretKey = generateAESKey();
File inputDir = new File("C:/input_files");
File outputDir = new File("C:/output_files");
// 加密操作
encryptDirectory(inputDir, outputDir, secretKey);
System.out.println("加密完成");
// 解密操作(演示,实际按需使用)
File decryptOutputDir = new File("C:/decrypt_output_files");
decryptDirectory(outputDir, decryptOutputDir, secretKey);
System.out.println("解密完成");
} catch (Exception e) {
e.printStackTrace();
}
}
}
(二)代码说明
- 密钥生成:
generateAESKey
方法创建 128 位 AES 密钥,可根据需求调整密钥长度(需配套修改环境策略文件 )。 - 加解密核心:
encryptFile
和decryptFile
利用Cipher
类,结合密钥对文件流进行加解密处理,采用AES/ECB/PKCS5Padding
模式(ECB 模式安全性稍弱,实际生产可考虑更安全的 CBC 等模式,需额外处理 IV 向量 )。 - 批量处理:
encryptDirectory
和decryptDirectory
递归遍历目录,对文件加密(输出带.enc
后缀文件 )、解密(还原原文件名 ),支持嵌套目录结构 。 - 主函数:
main
方法演示加解密流程,需替换inputDir
、outputDir
等路径为实际本地路径 。
四、使用说明
- 环境准备:确保安装 Java 开发环境(JDK 8 及以上 ),无需额外依赖。
- 配置与运行:
- 修改
main
方法中inputDir
(待加密文件目录 )、outputDir
(加密后文件输出目录 )等路径。 - 直接运行
FileEncryptor
类,观察控制台输出,加密后文件会生成在指定输出目录,解密操作同理(可按需拆分加密、解密逻辑 )。
- 修改
- 注意事项:
- 密钥安全:实际应用中,密钥需妥善保管(如通过安全配置中心、环境变量等方式存储 ),示例中直接生成密钥仅作演示,重启程序后密钥丢失会导致无法解密 。
- 文件兼容性:当前仅处理常见文件类型,若涉及特殊二进制文件,需验证加解密后完整性;加密后的
.enc
文件需对应解密逻辑还原 。 - 加密模式优化:生产环境建议替换 ECB 模式,采用 CBC、GCM 等更安全模式,需补充 IV(初始化向量 )生成与传递逻辑 。
五、扩展与优化方向
- 密钥管理增强:集成密钥管理系统(KMS ),或通过命令行参数、配置文件安全传入密钥,避免硬编码风险 。
- 加密模式升级:替换为
AES/GCM/NoPadding
等更安全模式,添加 IV 向量生成、验证逻辑,提升加密安全性 。 - 交互优化:开发图形化界面(如结合 Swing、JavaFX ),让用户通过界面选择目录、设置密钥,降低使用门槛 。
- 性能优化:针对大文件、海量文件场景,引入多线程并行加解密,提升处理效率 。