Java文件和文件夹加密和解密

文件加密和解密

使用AES算法进行加密和解密的操作

AEC是高级加密标准(Advanced Encryption Standard)的缩写,是一种对称密钥加密算法,常用于数据加密和保护隐私。

package com.sin.utils;

import javax.crypto.*;
import javax.crypto.spec.SecretKeySpec;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;

/**
 * @createTime 2023/10/18 11:24
 * @createAuthor SIN
 * @use 文件的加密和解密
 */
public class DocumentEncryptionUtil {
    // 文件的加密方式
    private static final String ALGORITHM = "AES";

    /**
     * 文件加密
     * @param secretKey  文件加密密钥
     * @param sourceFilePath  需要加密文件地址
     * @param destinationFilePath  加密后文件地址
     */
    public static void encryptFile(String secretKey,String sourceFilePath, String destinationFilePath) throws NoSuchAlgorithmException, NoSuchPaddingException, InvalidKeyException, IOException {
        // 使用密钥字符串生成秘密密钥
        SecretKey secretKeySpec = new SecretKeySpec(secretKey.getBytes(), ALGORITHM);
        // 获取 AES 加密算法的实例
        Cipher cipher = Cipher.getInstance(ALGORITHM);
        // 使用秘密密钥初始化密码 cipher,设置为加密模式
        cipher.init(Cipher.ENCRYPT_MODE, secretKeySpec);

        // 获取源文件路径
        Path sourcePath = Paths.get(sourceFilePath);
        // 获取目标加密文件路径
        Path destinationPath = Paths.get(destinationFilePath);

        // 创建输入流,读取源文件
        try (InputStream inputStream = Files.newInputStream(sourcePath);
             // 创建输出流,写入加密文件
             OutputStream outputStream = Files.newOutputStream(destinationPath);
             // 创建密码输出流,连接到输出流,并使用密码 cipher 进行加密
             CipherOutputStream cipherOutputStream = new CipherOutputStream(outputStream, cipher)) {
            // 缓冲区大小
            byte[] buffer = new byte[4096];
            int bytesRead;
            // 读取源文件内容到缓冲区
            while ((bytesRead = inputStream.read(buffer)) != -1) {
                // 将加密后的数据写入加密文件
                cipherOutputStream.write(buffer, 0, bytesRead);
            }
        }
    }

    /**
     * 文件解密
     * @param secretKey 文件解密密钥
     * @param sourceFilePath 需要解密的文件地址
     * @param destinationFilePath 解密后的文件地址
     */

    public static void decryptFile(String secretKey,String sourceFilePath, String destinationFilePath) throws NoSuchAlgorithmException, NoSuchPaddingException, InvalidKeyException, IOException {
        SecretKey secretKeySpec = new SecretKeySpec(secretKey.getBytes(), ALGORITHM); // 使用密钥字符串生成秘密密钥
        Cipher cipher = Cipher.getInstance(ALGORITHM); // 获取 AES 加密算法的实例
        cipher.init(Cipher.DECRYPT_MODE, secretKeySpec); // 使用秘密密钥初始化密码 cipher,设置为解密模式

        Path sourcePath = Paths.get(sourceFilePath); // 获取源加密文件路径
        Path destinationPath = Paths.get(destinationFilePath); // 获取目标解密文件路径

        try (InputStream inputStream = Files.newInputStream(sourcePath); // 创建输入流,读取加密文件
             OutputStream outputStream = Files.newOutputStream(destinationPath); // 创建输出流,写入解密文件
             CipherInputStream cipherInputStream = new CipherInputStream(inputStream, cipher)) { // 创建密码输入流,连接到输入流,并使用密码 cipher 进行解密
            byte[] buffer = new byte[4096]; // 缓冲区大小
            int bytesRead;
            while ((bytesRead = cipherInputStream.read(buffer)) != -1) { // 读取加密文件内容到缓冲区
                outputStream.write(buffer, 0, bytesRead); // 将解密后的数据写入解密文件
            }
        }
    }


}

文件加密

目标文件即内容
请添加图片描述

package com.sin.utils.test;

import com.sin.utils.DocumentEncryptionUtil;
import org.junit.Test;

import javax.crypto.NoSuchPaddingException;
import java.io.IOException;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;

/**
 * @createTime 2023/10/18 11:28
 * @createAuthor SIN
 * @use
 */
public class DocumentEncryptionUtilTest {

    /**
     * 文件加密
     */
    @Test
    public void encryptFileTest(){
        try {
            DocumentEncryptionUtil.encryptFile("SIN-80238023-@@@","D:/FileEncryptionUtil.txt","D:/Demo/FileEncryptionUtil.txt");
        } catch (NoSuchAlgorithmException e) {
            throw new RuntimeException(e);
        } catch (NoSuchPaddingException e) {
            throw new RuntimeException(e);
        } catch (InvalidKeyException e) {
            throw new RuntimeException(e);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

加密后的文件
在这里插入图片描述

文件解密

 /**
     * 文件解密
     */
    @Test
    public void decryptFileTest(){
        try {
            DocumentEncryptionUtil.decryptFile("SIN-80238023-@@@","D:/Demo/FileEncryptionUtil.txt","D:/Demo/FileEncryptionUtil1.txt");
        } catch (NoSuchAlgorithmException e) {
            throw new RuntimeException(e);
        } catch (NoSuchPaddingException e) {
            throw new RuntimeException(e);
        } catch (InvalidKeyException e) {
            throw new RuntimeException(e);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

解密后的文件
在这里插入图片描述

文件夹加密和解密

package com.sin.utils;

import javax.crypto.*;
import javax.crypto.spec.SecretKeySpec;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.nio.file.DirectoryStream;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;

/**
 * @createTime 2023/10/19 9:20
 * @createAuthor SIN
 * @use 文件夹加密和解密
 */
public class FileEncryptionUtil {

    //AES是高级加密标准(Advanced Encryption Standard)的缩写,是一种对称密钥加密算法,常用于数据加密和保护隐私。
    private static final String ALGORITHM = "AES";


    /**
     * 去除文件名扩展名
     * @param fileName 需要操作的文件
     * @return
     */
    private static String removeExtension(String fileName) {
        // 找到文件的最后一个点
        int dotIndex = fileName.lastIndexOf(".");
        // 保证点不是文件名的第一个字符和最后一个字符
        if (dotIndex > 0 && dotIndex < fileName.length() - 1) {
            // 返回有效的扩展名
            return fileName.substring(0, dotIndex);
        }
        // 返回源文件
        return fileName;
    }

    /**
     * 文件夹加密
     * @param secretKey 文件夹加密密钥
     * @param sourceFilePath 需要加密的文件夹
     * @param destinationFilePath 加密后的文件夹地址
     */
    public static void encryptFile(String secretKey,String sourceFilePath, String destinationFilePath) throws NoSuchAlgorithmException, NoSuchPaddingException, InvalidKeyException, IOException {
        // 使用密钥字符串生成秘密密钥
        SecretKey secretKeySpec = new SecretKeySpec(secretKey.getBytes(), ALGORITHM);
        // 获取 AES 加密算法的实例
        Cipher cipher = Cipher.getInstance(ALGORITHM);
        // 使用秘密密钥初始化密码 cipher,设置为加密模式
        cipher.init(Cipher.ENCRYPT_MODE, secretKeySpec);

        // 获取源文件或文件夹路径
        Path sourcePath = Paths.get(sourceFilePath);
        // 获取目标加密文件或文件夹路径
        Path destinationPath = Paths.get(destinationFilePath);

        if (Files.isDirectory(sourcePath) && !Files.exists(destinationPath)) {
            // 创建目标文件夹
            Files.createDirectories(destinationPath);
            // 遍历源文件夹
            try (DirectoryStream<Path> directoryStream = Files.newDirectoryStream(sourcePath)) {
                for (Path filePath : directoryStream) {
                    // 加密后的文件名
                    String encryptedFileName = filePath.getFileName().toString() + ".enc";
                    // 加密后的文件路径
                    String encryptedFilePath = destinationPath.resolve(encryptedFileName).toString();
                    // 递归调用加密方法,处理子文件或子文件夹
                    encryptFile(secretKey,filePath.toString(), encryptedFilePath);
                }
            }
        } else if (Files.isRegularFile(sourcePath)) {
            // 创建输入流,读取源文件
            try (InputStream inputStream = Files.newInputStream(sourcePath);
                 // 创建输出流,写入加密文件
                 OutputStream outputStream = Files.newOutputStream(destinationPath);
                 // 创建密码输出流,连接到输出流,并使用密码 cipher 进行加密
                 CipherOutputStream cipherOutputStream = new CipherOutputStream(outputStream, cipher)) {
                // 缓冲区大小
                byte[] buffer = new byte[4096];
                int bytesRead;
                // 读取源文件内容到缓冲区
                while ((bytesRead = inputStream.read(buffer)) != -1) {
                    // 将加密后的数据写入加密文件
                    cipherOutputStream.write(buffer, 0, bytesRead);
                }
            }
        }
    }

    /**
     *
     * @param secretKey 文件夹解密密钥
     * @param sourceFilePath 需要解密的文件夹
     * @param destinationFilePath 解密后的文件夹地址
     */
    public static void decryptFile(String secretKey,String sourceFilePath, String destinationFilePath) throws NoSuchAlgorithmException, NoSuchPaddingException, InvalidKeyException, IOException {
        SecretKey secretKeySpec = new SecretKeySpec(secretKey.getBytes(), ALGORITHM); // 使用密钥字符串生成秘密密钥
        Cipher cipher = Cipher.getInstance(ALGORITHM); // 获取 AES 加密算法的实例
        cipher.init(Cipher.DECRYPT_MODE, secretKeySpec); // 使用秘密密钥初始化密码 cipher,设置为解密模式

        Path sourcePath = Paths.get(sourceFilePath); // 获取源加密文件或文件夹路径
        Path destinationPath = Paths.get(destinationFilePath); // 获取目标解密文件或文件夹路径

        if (Files.isDirectory(sourcePath) && !Files.exists(destinationPath)) {
            Files.createDirectories(destinationPath); // 创建目标文件夹
            try (DirectoryStream<Path> directoryStream = Files.newDirectoryStream(sourcePath)) { // 遍历源文件夹
                for (Path filePath : directoryStream) {
                    String decryptedFileName = removeExtension(filePath.getFileName().toString()); // 去除文件名的扩展名
                    String decryptedFilePath = destinationPath.resolve(decryptedFileName).toString(); // 解密后的文件路径
                    decryptFile(secretKey,filePath.toString(), decryptedFilePath); // 递归调用解密方法,处理子文件或子文件夹
                }
            }
        } else if (Files.isRegularFile(sourcePath)) {
            try (InputStream inputStream = Files.newInputStream(sourcePath); // 创建输入流,读取加密文件
                 OutputStream outputStream = Files.newOutputStream(destinationPath); // 创建输出流,写入解密文件
                 CipherInputStream cipherInputStream = new CipherInputStream(inputStream, cipher)) { // 创建密码输入流,连接到输入流,并使用密码 cipher 进行解密
                byte[] buffer = new byte[4096]; // 缓冲区大小
                int bytesRead;
                while ((bytesRead = cipherInputStream.read(buffer)) != -1) { // 读取加密文件内容到缓冲区
                    outputStream.write(buffer, 0, bytesRead); // 将解密后的数据写入解密文件
                }
            }
        }
    }

}

需要加密的文件
在这里插入图片描述

加密文件

package com.sin.utils.test;

import com.sin.utils.FileEncryptionUtil;
import org.junit.Test;

import javax.crypto.NoSuchPaddingException;
import java.io.IOException;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;

/**
 * @createTime 2023/10/19 9:32
 * @createAuthor SIN
 * @use 测试文件夹加密和解密
 */
public class FileEncryptionUtilTest {

    /**
     * 加密文件
     */
    @Test
    public void encryptFileTest(){
        try {
            FileEncryptionUtil.encryptFile("sin-80238023-@@@","D:/Demo","D:/Demo1");
        } catch (NoSuchAlgorithmException e) {
            throw new RuntimeException(e);
        } catch (NoSuchPaddingException e) {
            throw new RuntimeException(e);
        } catch (InvalidKeyException e) {
            throw new RuntimeException(e);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

加密后的文件
在这里插入图片描述

解密文件

/**
 * 解密文件
 */
@Test
public void decryptFile(){
    try {
        FileEncryptionUtil.decryptFile("sin-80238023-@@@","D:/Demo1","D:/Demo2");
    } catch (NoSuchAlgorithmException e) {
        throw new RuntimeException(e);
    } catch (NoSuchPaddingException e) {
        throw new RuntimeException(e);
    } catch (InvalidKeyException e) {
        throw new RuntimeException(e);
    } catch (IOException e) {
        throw new RuntimeException(e);
    }
}

解密后的文件

在这里插入图片描述

  • 6
    点赞
  • 28
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 1
    评论
Java文件压缩加密是一种将Java文件进行压缩和加密保护的技术。通过对文件进行压缩,可以减小文件的体积,方便传输和存储。而通过加密文件,可以保护文件的内容,防止未经授权的人员获取和修改文件。 在Java中,可以使用压缩和加密相关的类和方法来实现文件压缩加密操作。常用的压缩类有java.util.zip.ZipOutputStream和java.util.zip.ZipInputStream,通过这些类可以将文件文件夹压缩为zip格式的压缩包,或者解压缩已有的压缩包。 对于文件加密,可以使用Java提供的加密算法和密码库来实现。常用的加密算法有对称加密算法和非对称加密算法。对称加密算法如AES和DES可以使用相同的密钥进行加密解密,而非对称加密算法如RSA则需要一对公钥和私钥进行加密解密。通过在程序中使用对应的算法和密钥,可以将文件内容加密后保存,只有使用正确的密钥才能解密文件内容。 在实现文件压缩加密时,可以先将文件进行压缩,然后再对压缩后的文件进行加密操作。这样可以同时达到减小文件体积和保护文件内容的目的。在传输或存储文件时,可以先解密再解压缩,得到原始的文件内容。 总之,Java文件压缩加密是一种通过压缩和加密的方式保护文件内容的技术,通过使用Java提供的压缩和加密类、算法和密码库,可以方便地实现文件的压缩和加密操作

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

陆卿之

你的鼓励将是我最大的动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值