Java中的文件加密:从基础到实践

引言

在数字化时代,数据安全至关重要。文件加密是保护敏感信息不被未授权访问的有效手段。Java作为企业级应用开发的主流语言,提供了强大的加密库——Java Cryptography Extension (JCE),使得加密操作既安全又便捷。本文将从基础出发,详细介绍如何在Java中实现文件加密。

加密基础

对称加密与非对称加密

加密算法主要分为对称加密和非对称加密。对称加密使用相同的密钥进行加密和解密,速度快,适合大文件加密。非对称加密使用公钥和私钥,安全性更高但性能较低。对于文件加密,通常使用对称加密(如AES)配合密钥管理。

常见对称加密算法

  • AES(高级加密标准):目前最常用的对称加密算法,支持128、192、256位密钥。
  • DES:数据加密标准,现已不安全,不建议使用。
  • 3DES:三重DES,安全性中等,但性能较差。

Java加密库

Java提供了javax.crypto包,其中包含CipherKeyGeneratorSecretKey等核心类。使用前需导入以下包:

import javax.crypto.Cipher;
import javax.crypto.KeyGenerator;
import javax.crypto.SecretKey;
import javax.crypto.spec.SecretKeySpec;
import java.security.NoSuchAlgorithmException;
import java.util.Base64;

密钥生成与管理

对于AES加密,密钥长度通常为128、192或256位。生成密钥的示例:

KeyGenerator keyGen = KeyGenerator.getInstance("AES");
keyGen.init(128); // 128位密钥
SecretKey secretKey = keyGen.generateKey();

密钥通常以字节数组形式保存,可以使用Base64编码存储为字符串。

文件加密步骤

  1. 读取原始文件为字节数组。
  2. 创建Cipher实例并初始化为加密模式。
  3. 调用doFinal()方法加密数据。
  4. 将加密后的字节数组写入新文件。

示例代码:AES文件加密

import javax.crypto.Cipher;
import javax.crypto.KeyGenerator;
import javax.crypto.SecretKey;
import javax.crypto.spec.SecretKeySpec;
import java.io.*;
import java.security.NoSuchAlgorithmException;
import java.util.Base64;

public class FileEncryptor {
    private static final String ALGORITHM = "AES";
    private static final String TRANSFORMATION = "AES/ECB/PKCS5Padding";

    public static void encrypt(SecretKey key, File inputFile, File outputFile) throws Exception {
        Cipher cipher = Cipher.getInstance(TRANSFORMATION);
        cipher.init(Cipher.ENCRYPT_MODE, key);
        try (FileInputStream fis = new FileInputStream(inputFile);
             FileOutputStream fos = new FileOutputStream(outputFile)) {
            byte[] inputBytes = new byte[(int) inputFile.length()];
            fis.read(inputBytes);
            byte[] outputBytes = cipher.doFinal(inputBytes);
            fos.write(outputBytes);
        }
    }

    public static void decrypt(SecretKey key, File inputFile, File outputFile) throws Exception {
        Cipher cipher = Cipher.getInstance(TRANSFORMATION);
        cipher.init(Cipher.DECRYPT_MODE, key);
        try (FileInputStream fis = new FileInputStream(inputFile);
             FileOutputStream fos = new FileOutputStream(outputFile)) {
            byte[] inputBytes = new byte[(int) inputFile.length()];
            fis.read(inputBytes);
            byte[] outputBytes = cipher.doFinal(inputBytes);
            fos.write(outputBytes);
        }
    }

    public static void main(String[] args) throws Exception {
        KeyGenerator keyGen = KeyGenerator.getInstance("AES");
        keyGen.init(128);
        SecretKey secretKey = keyGen.generateKey();
        
        File original = new File("original.txt");
        File encrypted = new File("encrypted.enc");
        File decrypted = new File("decrypted.txt");
        
        encrypt(secretKey, original, encrypted);
        decrypt(secretKey, encrypted, decrypted);
    }
}

密钥存储与传输

密钥文件应妥善保管。可以将其存储为Base64字符串,或使用密钥库(KeyStore)。在传输时,可使用非对称加密保护对称密钥。

安全性考虑

  • 使用安全的随机数生成器(如SecureRandom)来生成密钥。
  • 避免使用ECB模式(示例中使用仅作演示),推荐使用CBC或GCM模式。
  • 在加密大文件时,使用CipherInputStreamCipherOutputStream进行流式处理,避免内存溢出。
  • 妥善处理异常,避免泄露敏感信息。

总结

本文介绍了Java中文件加密的基本原理和实现方法。通过AES对称加密,可以高效地保护文件数据。实际应用中,需要结合具体场景选择合适的加密模式和密钥管理策略,确保数据安全。