import javax.crypto.Cipher;
import javax.crypto.KeyGenerator;
import javax.crypto.SecretKey;
import javax.crypto.spec.SecretKeySpec;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.Base64;
public class FileEncryptionExample {
    private static final String ALGORITHM = "AES";
    private static final String TRANSFORMATION = "AES";
    public static void main(String[] args) {
        try {
            // 生成密钥
            KeyGenerator keyGen = KeyGenerator.getInstance(ALGORITHM);
            keyGen.init(128); // 使用128位密钥长度
            SecretKey secretKey = keyGen.generateKey();
            byte[] encodedKey = secretKey.getEncoded();
            String encodedKeyString = Base64.getEncoder().encodeToString(encodedKey);
            System.out.println("Generated Key: " + encodedKeyString);
            // 加密文件
            File inputFile = new File("input.txt");
            File encryptedFile = new File("encrypted.bin");
            encrypt(encodedKey, inputFile, encryptedFile);
            // 解密文件
            File decryptedFile = new File("decrypted.txt");
            decrypt(encodedKey, encryptedFile, decryptedFile);
            System.out.println("Encryption and Decryption completed successfully.");
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
    public static void encrypt(byte[] key, File inputFile, File outputFile) throws Exception {
        doCrypto(Cipher.ENCRYPT_MODE, key, inputFile, outputFile);
    }
    public static void decrypt(byte[] key, File inputFile, File outputFile) throws Exception {
        doCrypto(Cipher.DECRYPT_MODE, key, inputFile, outputFile);
    }
    private static void doCrypto(int cipherMode, byte[] key, File inputFile, File outputFile) throws Exception {
        try (FileInputStream inputStream = new FileInputStream(inputFile);
             FileOutputStream outputStream = new FileOutputStream(outputFile)) {
            SecretKeySpec secretKeySpec = new SecretKeySpec(key, ALGORITHM);
            Cipher cipher = Cipher.getInstance(TRANSFORMATION);
            cipher.init(cipherMode, secretKeySpec);
            byte[] inputBytes = new byte[(int) inputFile.length()];
            inputStream.read(inputBytes);
            byte[] outputBytes = cipher.doFinal(inputBytes);
            outputStream.write(outputBytes);
        }
    }
}生成密钥:
KeyGenerator 类生成一个 AES 密钥,并将其编码为 Base64 字符串以便存储或传输。加密文件:
encrypt 方法使用生成的密钥对输入文件进行加密,并将加密后的数据写入输出文件。doCrypto 方法负责实际的加密操作,它初始化 Cipher 对象并处理文件的读取和写入。解密文件:
decrypt 方法使用相同的密钥对加密文件进行解密,并将解密后的数据写入新的输出文件。注意点:
Laravel PHP 深圳智简公司。版权所有©2023-2043 LaravelPHP 粤ICP备2021048745号-3
Laravel 中文站