java如何對(duì)文件流加密

小億
125
2023-12-29 16:33:33

Java可以使用密碼流對(duì)文件流進(jìn)行加密。密碼流是Java IO庫(kù)提供的一種特殊的輸入/輸出流,它可以對(duì)底層的文件流進(jìn)行加密和解密操作。下面是一個(gè)簡(jiǎn)單的示例代碼,展示了如何使用密碼流對(duì)文件進(jìn)行加密。

import java.io.*;
import javax.crypto.*;
import javax.crypto.spec.SecretKeySpec;

public class FileEncryption {
    public static void main(String[] args) {
        String sourceFile = "source.txt";
        String encryptedFile = "encrypted.txt";
        String decryptedFile = "decrypted.txt";
        String key = "1234567890abcdef"; // 密鑰,16位字符

        try {
            encrypt(sourceFile, encryptedFile, key);
            System.out.println("文件加密成功!");
            
            decrypt(encryptedFile, decryptedFile, key);
            System.out.println("文件解密成功!");
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public static void encrypt(String sourceFile, String encryptedFile, String key) throws Exception {
        File inputFile = new File(sourceFile);
        File outputFile = new File(encryptedFile);

        FileInputStream inputStream = new FileInputStream(inputFile);
        FileOutputStream outputStream = new FileOutputStream(outputFile);

        SecretKeySpec secretKeySpec = new SecretKeySpec(key.getBytes(), "AES");
        Cipher cipher = Cipher.getInstance("AES");
        cipher.init(Cipher.ENCRYPT_MODE, secretKeySpec);

        CipherOutputStream cipherOutputStream = new CipherOutputStream(outputStream, cipher);

        byte[] buffer = new byte[1024];
        int bytesRead;
        while ((bytesRead = inputStream.read(buffer)) != -1) {
            cipherOutputStream.write(buffer, 0, bytesRead);
        }

        cipherOutputStream.close();
        inputStream.close();
    }

    public static void decrypt(String encryptedFile, String decryptedFile, String key) throws Exception {
        File inputFile = new File(encryptedFile);
        File outputFile = new File(decryptedFile);

        FileInputStream inputStream = new FileInputStream(inputFile);
        FileOutputStream outputStream = new FileOutputStream(outputFile);

        SecretKeySpec secretKeySpec = new SecretKeySpec(key.getBytes(), "AES");
        Cipher cipher = Cipher.getInstance("AES");
        cipher.init(Cipher.DECRYPT_MODE, secretKeySpec);

        CipherInputStream cipherInputStream = new CipherInputStream(inputStream, cipher);

        byte[] buffer = new byte[1024];
        int bytesRead;
        while ((bytesRead = cipherInputStream.read(buffer)) != -1) {
            outputStream.write(buffer, 0, bytesRead);
        }

        outputStream.close();
        cipherInputStream.close();
    }
}

在上面的示例中,我們使用了AES算法對(duì)文件進(jìn)行加密和解密。需要注意的是,AES算法需要一個(gè)16位的密鑰,因此我們?cè)诖a中使用了一個(gè)16位的字符串作為密鑰。實(shí)際應(yīng)用中,你可能需要使用更安全的密鑰生成方式。

這只是一個(gè)簡(jiǎn)單的示例,真實(shí)情況下你可能需要處理更多的異常情況,并采用更安全的加密方式。

0