文件IO和AES加密

文件的上传 和 下载

读取文件

@Test
public void testInputStream(){
    InputStream inputStream = null;
    try {
        // InputStream 读取文件
        inputStream = new FileInputStream("test.txt");
        // 设置文件读取的缓冲区大小 数组
        byte[] bytes = new byte[1024];
        // 记录读取的字节数
        int len = 0;
        // 循环读取文件
        while ((len = inputStream.read(bytes))!= -1) {
            System.out.println(new String(bytes, 0, len));
        }
    } catch (IOException e) {
        throw new RuntimeException(e);
    }finally {
        // 关闭流
        if (inputStream!= null) {
            try {
                inputStream.close();
            }catch (IOException e){
                throw new RuntimeException(e);
            }
        }
    }
}

读取 和 写入 文件

package cn.djx.springio;

import org.junit.jupiter.api.Test;
import org.springframework.boot.test.context.SpringBootTest;

import java.io.*;

@SpringBootTest
class SpringIoApplicationTests {
    @Test
    public void testInputStream(){
        InputStream inputStream = null;
        try {
            // InputStream 读取文件
            inputStream = new FileInputStream("test.txt");
            // 设置文件读取的缓冲区大小 数组
            byte[] bytes = new byte[1024];
            // 记录读取的字节数
            int len = 0;
            // 循环读取文件
            while ((len = inputStream.read(bytes))!= -1) {
                System.out.println(new String(bytes, 0, len));
            }
        } catch (IOException e) {
            throw new RuntimeException(e);
        }finally {
            // 关闭流
            if (inputStream!= null) {
                try {
                    inputStream.close();
                }catch (IOException e){
                    throw new RuntimeException(e);
                }
            }
        }
    }
    @Test
    public void testInputStreamAndOutputStream(){
        InputStream inputStream = null;
        OutputStream outputStream = null;
        try {
            // InputStream 读取文件
            inputStream = new FileInputStream("test.txt");
            // OutputStream 写入文件
            outputStream = new FileOutputStream("test_copy.txt");
            // 设置文件读取的缓冲区大小 数组
            byte[] bytes = new byte[1024];
            // 记录读取的字节数
            int len = 0;
            // 循环读取文件
            while ((len = inputStream.read(bytes))!= -1) {
                // 写入文件
                outputStream.write(bytes, 0, len);
                // 刷新缓冲区 可与预防数据丢失
                outputStream.flush();
            }
        } catch (IOException e) {
            throw new RuntimeException(e);
        } if (inputStream!= null) {
            // 关闭流
            try {
                inputStream.close();
                outputStream.close();
            }catch (IOException e){
                throw new RuntimeException(e);
            }
        }
    }

}

AES 加密

引入了依赖

       <dependency>
            <groupId>cn.hutool</groupId>
            <artifactId>hutool-crypto</artifactId>
            <version>5.8.28</version>
        </dependency>

测试代码

package cn.djx.springfile;

import cn.hutool.core.util.CharsetUtil;
import cn.hutool.crypto.SecureUtil;
import cn.hutool.crypto.symmetric.AES;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.test.context.SpringBootTest;

import java.io.*;

@SpringBootTest
class SpringFileApplicationTests {
    @Value("${aes.key}")
    public String aesKey;
    @Test
    void testAES() {
        String content = "Hello, Spring Boot!";
        byte[] key = aesKey.getBytes();
        //AES aes = new AES(key);
        AES aes = SecureUtil.aes(aesKey.getBytes());
        // 加密
        byte[] encrypt = aes.encrypt(content);
        // 解密
        String decrypt = aes.decryptStr(encrypt);

        // 加密为16进制表示
        String encryptHex = aes.encryptHex(content);
        // 解密为字符串
        String decryptStr = aes.decryptStr(encryptHex, CharsetUtil.CHARSET_UTF_8);

    }
    @Test
    public void testEncrypt(){
        AES aes = SecureUtil.aes(aesKey.getBytes());

        // 文件的操作
        InputStream inputStream = null;
        OutputStream outputStream = null;
        try {
            // InputStream 读取文件
            inputStream = new FileInputStream("test.png");
            // OutputStream 写入文件
            outputStream = new FileOutputStream("test_encrypt.png");
            // 设置文件读取的缓冲区大小 数组
            byte[] bytes = inputStream.readAllBytes();
            byte[] aesBytes = aes.encrypt(bytes);
            // 写入文件
            outputStream.write(aesBytes);
            // 刷新缓冲区 可与预防数据丢失
            outputStream.flush();

        } catch (IOException e) {
            throw new RuntimeException(e);
        } if (inputStream!= null) {
            // 关闭流
            try {
                inputStream.close();
                outputStream.close();
            }catch (IOException e){
                throw new RuntimeException(e);
            }
        }
    }
    @Test
    public void testDecrypt(){
        AES aes = SecureUtil.aes(aesKey.getBytes());

        // 文件的操作
        InputStream inputStream = null;
        OutputStream outputStream = null;
        try {
            // InputStream 读取文件
            inputStream = new FileInputStream("test_encrypt.png");
            // OutputStream 写入文件
            outputStream = new FileOutputStream("test_decrypt.png");
            // 设置文件读取的缓冲区大小 数组
            byte[] bytes = inputStream.readAllBytes();

            // 写入文件 并解密
            outputStream.write(aes.decrypt(bytes));
            // 刷新缓冲区 可与预防数据丢失
            outputStream.flush();

        } catch (IOException e) {
            throw new RuntimeException(e);
        } if (inputStream!= null) {
            // 关闭流
            try {
                inputStream.close();
                outputStream.close();
            }catch (IOException e){
                throw new RuntimeException(e);
            }
        }
    }

}

源文件

加密文件

解密文件

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
### 回答1: 在Java中,可以使用javax.crypto包中的AES算法来实现文件的加密。 首先,需要导入相应的包: ``` import javax.crypto.Cipher; import javax.crypto.spec.SecretKeySpec; import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import java.security.Key; ``` 然后,编写一个方法来实现AES加密文件的功能: ```java public static void encryptFile(String filePath, String key, String outputFilePath) { try { File inputFile = new File(filePath); FileInputStream fis = new FileInputStream(inputFile); byte[] inputBytes = new byte[(int) inputFile.length()]; fis.read(inputBytes); Key aesKey = new SecretKeySpec(key.getBytes(), "AES"); Cipher cipher = Cipher.getInstance("AES"); cipher.init(Cipher.ENCRYPT_MODE, aesKey); byte[] encryptedBytes = cipher.doFinal(inputBytes); FileOutputStream fos = new FileOutputStream(outputFilePath); fos.write(encryptedBytes); fis.close(); fos.close(); } catch (Exception e) { e.printStackTrace(); } } ``` 以上的代码实现了输入一个文件路径(filePath)、一个密钥(key)和一个输出文件路径(outputFilePath),然后加密该文件。 使用方法: ```java public static void main(String[] args) { String filePath = "input.txt"; String key = "0123456789abcdef"; String outputFilePath = "encrypted.txt"; encryptFile(filePath, key, outputFilePath); } ``` 以上代码会将名为"input.txt"的文件加密并输出为"encrypted.txt"。 需要注意的是,以上代码只是简单实现了AES加密文件的功能,实际使用中还需要处理异常、进行错误处理等等,提供更完整的功能。 ### 回答2: 要使用Java代码实现AES加密文件,首先需要导入相关的库文件。可以使用Java标准库中的javax.crypto包实现AES加密。以下是一个简单的实现示例: ```java import javax.crypto.Cipher; import javax.crypto.spec.SecretKeySpec; import java.io.FileInputStream; import java.io.FileOutputStream; import java.security.Key; import java.util.Arrays; public class AESFileEncryption { // 提供密钥,注意密钥长度必须为16的倍数,因为AES加密算法使用的是128位密钥 private static final byte[] keyBytes = "0123456789abcdef".getBytes(); public static void main(String[] args) { encryptFile("input.txt", "encrypted.txt"); decryptFile("encrypted.txt", "decrypted.txt"); } public static void encryptFile(String inputFile, String outputFile) { try { FileInputStream fis = new FileInputStream(inputFile); FileOutputStream fos = new FileOutputStream(outputFile); Key key = new SecretKeySpec(keyBytes, "AES"); Cipher cipher = Cipher.getInstance("AES"); cipher.init(Cipher.ENCRYPT_MODE, key); byte[] inputBytes = new byte[1024]; int bytesRead; while ((bytesRead = fis.read(inputBytes)) != -1) { byte[] outputBytes = cipher.update(inputBytes, 0, bytesRead); if (outputBytes != null) { fos.write(outputBytes); } } byte[] outputBytes = cipher.doFinal(); if (outputBytes != null) { fos.write(outputBytes); } fis.close(); fos.close(); System.out.println("文件加密成功!"); } catch (Exception e) { e.printStackTrace(); } } public static void decryptFile(String inputFile, String outputFile) { try { FileInputStream fis = new FileInputStream(inputFile); FileOutputStream fos = new FileOutputStream(outputFile); Key key = new SecretKeySpec(keyBytes, "AES"); Cipher cipher = Cipher.getInstance("AES"); cipher.init(Cipher.DECRYPT_MODE, key); byte[] inputBytes = new byte[1024]; int bytesRead; while ((bytesRead = fis.read(inputBytes)) != -1) { byte[] outputBytes = cipher.update(inputBytes, 0, bytesRead); if (outputBytes != null) { fos.write(outputBytes); } } byte[] outputBytes = cipher.doFinal(); if (outputBytes != null) { fos.write(outputBytes); } fis.close(); fos.close(); System.out.println("文件解密成功!"); } catch (Exception e) { e.printStackTrace(); } } } ``` 在这个示例中,我们使用了一个预定义的密钥`0123456789abcdef`,你可以根据需要更改这个密钥。该示例将输入文件`input.txt`进行加密,并将加密后的数据写入到输出文件`encrypted.txt`中。然后再将加密后的文件`encrypted.txt`进行解密,并将解密后的数据写入到输出文件`decrypted.txt`中。 请注意,在实际应用中,应该使用更加安全的方法来存储密钥,例如使用密钥管理服务(Key Management Service)或者使用密钥派生函数来生成密钥。此外,还应该考虑更加完善的错误处理和异常处理机制。这个示例只是一个简单的加密文件的实现,实际使用时还需要根据具体需求进行修改和完善。 ### 回答3: 要实现Java代码中的AES加密文件,可以按照以下步骤: 第一步,引入所需的Java库。在代码的开头,需要引入javax.crypto包中的一些类,包括Cipher、SecretKeySpec和IvParameterSpec等。 第二步,指定密钥和IV向量。AES算法需要一个密钥和一个16字节的IV向量。可以自己生成密钥和IV向量,也可以利用密码学安全随机数生成器进行生成。 第三步,创建Cipher对象并初始化。使用AES算法创建一个Cipher对象,并指定加密模式和填充模式。可以使用"CBC"模式,同时选择"PKCS5Padding"填充模式。 第四步,创建输入输出流。使用Java的FileInputStream类创建一个输入流,读取待加密的文件。同时,还需要创建一个FileOutputStream类的对象,用于写入加密后的文件。 第五步,加密处理。在一个循环中,读取输入流中的数据,并使用Cipher对象的update方法对数据进行加密,然后将加密结果写入输出流中。 第六步,处理最后的块。在处理最后的数据块时,需要使用Cipher对象的doFinal方法来进行加密,并将最终的结果写入输出流中。 第七步,关闭流。在加密完成后,需要将输入输出流进行关闭,释放资源。 完整的代码示例如下: ``` import javax.crypto.Cipher; import javax.crypto.SecretKey; import javax.crypto.spec.IvParameterSpec; import javax.crypto.spec.SecretKeySpec; import java.io.FileInputStream; import java.io.FileOutputStream; import java.security.SecureRandom; public class AESEncryption { public static void main(String[] args) { String inputFile = "input.txt"; String encryptedFile = "encrypted.txt"; String key = "0123456789ABCDEF"; String iv = "0123456789ABCDEF"; try { FileInputStream fis = new FileInputStream(inputFile); FileOutputStream fos = new FileOutputStream(encryptedFile); byte[] keyBytes = key.getBytes("UTF-8"); SecretKey secretKey = new SecretKeySpec(keyBytes, "AES"); byte[] ivBytes = iv.getBytes("UTF-8"); IvParameterSpec ivSpec = new IvParameterSpec(ivBytes); Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding"); cipher.init(Cipher.ENCRYPT_MODE, secretKey, ivSpec); byte[] inputBuffer = new byte[1024]; int bytesRead; while ((bytesRead = fis.read(inputBuffer)) != -1) { byte[] outputBuffer = cipher.update(inputBuffer, 0, bytesRead); if (outputBuffer != null) { fos.write(outputBuffer); } } byte[] outputBuffer = cipher.doFinal(); if (outputBuffer != null) { fos.write(outputBuffer); } fis.close(); fos.flush(); fos.close(); System.out.println("文件加密成功!"); } catch (Exception e) { e.printStackTrace(); } } } ``` 以上就是使用Java代码实现AES加密文件的步骤概述和代码示例。根据实际需求,可以进行适当的修改和调整。
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值