java如何对文件流加密

   2025-02-13 8560
核心提示:Java可以使用密码流对文件流进行加密。密码流是Java IO库提供的一种特殊的输入/输出流,它可以对底层的文件流进行加密和解密操作

Java可以使用密码流对文件流进行加密。密码流是Java IO库提供的一种特殊的输入/输出流,它可以对底层的文件流进行加密和解密操作。下面是一个简单的示例代码,展示了如何使用密码流对文件进行加密。

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算法对文件进行加密和解密。需要注意的是,AES算法需要一个16位的密钥,因此我们在代码中使用了一个16位的字符串作为密钥。实际应用中,你可能需要使用更安全的密钥生成方式。

这只是一个简单的示例,真实情况下你可能需要处理更多的异常情况,并采用更安全的加密方式。

 
 
更多>同类维修知识
推荐图文
推荐维修知识
点击排行
网站首页  |  关于我们  |  联系方式  |  用户协议  |  隐私政策  |  网站留言