【生成指定分隔符的文件并加密压缩】

该博客介绍了一个Java实现的文件处理类,包括使用CSV格式生成文件,使用SM4算法进行文件加密,以及将加密文件进行ZIP压缩。整个过程确保了数据的安全性和压缩效率。文件操作涉及到了文件的创建、加密、压缩和删除。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

生成指定分隔符的文件并加密

生成文件

public class FileSM4AndZip {

    /**
     * CSV文件列分隔符
     */
    private static final String CSV_COLUMN_SEPARATOR = "\u001B";

    /**
     * CSV文件行分隔符
     */
    private static final String CSV_ROW_SEPARATOR = "\n";

    /**
     * 加密  压缩
     * @param fileName 原始文件 如:/data/upload/test.bat
     */
    public static void fileEncAndZip(String fileName, String[] titleColumn, List<Map<String, Object>> dataList,String filePath, String year, String month){
        String name =  fileName + ".dat";
        // 生成文件
        filePath = createFile(name, titleColumn, dataList,filePath, year, month);
        
        String encFileName =filePath + fileName + ".sm4";
        
        String zipFileName =filePath + fileName + ".zip";

        // 文件内容加密
        SM4Tools.encryptFile( filePath + name, encFileName);
        // 文件压缩
        FileZip.compression( zipFileName,new File( encFileName));

        File file = new File(filePath + name);
        file.delete();
        File file1 = new File(encFileName);
        file1.delete();

    }



    private static String createFile( String fileName, String[] titleColumn, List<Map<String, Object>> dataList,String filePath, String year, String month) {
        OutputStream out = null;
        try {
             filePath = filePath + year + "\\" + month + "\\";

            String path = filePath + fileName;
            File file = new File(path);
            if (!file.getParentFile().exists()) {
                file.getParentFile().mkdirs();
            }
            if (!file.exists()) {
                file.createNewFile();
            }
            out = new FileOutputStream(path);


            //保证线程安全
            StringBuilder buf = new StringBuilder();

            //组装行数据
            for (Map<String, Object> map : dataList) {
                for (int i = 0; i < titleColumn.length; i++) {
                    String title = titleColumn[i].trim();
                    if (!"".equals(title)) {
                        //组装数据
                        buf.append(map.get(title));
                        if (i != titleColumn.length - 1) {
                            buf.append(CSV_COLUMN_SEPARATOR);
                        }
                    }
                }
                buf.append(CSV_ROW_SEPARATOR);
            }
            //输出
            out.write(buf.toString().getBytes(StandardCharsets.UTF_8));
            return filePath;
        } catch (IOException e) {
            throw new RuntimeException(e);
        } finally {
            if (out != null) {
                try {
                    out.flush();
                    out.close();
                } catch (IOException ignored) {
                }
            }
        }
    }

}

sm4 加密

public class SM4Tools {

    private static final String key = "C7046F00DWID8583F1AB0AJFNA5E470E";
    private static final byte[] keyData = ByteUtils.fromHexString(key);

    static{
        if (Security.getProvider(BouncyCastleProvider.PROVIDER_NAME) == null){
            //No such provider: BC
            Security.addProvider(new BouncyCastleProvider());
        }
    }

    //生成 Cipher
    public static Cipher generateCipher(int mode,byte[] keyData) throws InvalidKeyException, NoSuchPaddingException, NoSuchAlgorithmException, NoSuchProviderException {
        Cipher cipher = Cipher.getInstance("SM4/ECB/PKCS5Padding", BouncyCastleProvider.PROVIDER_NAME);
        Key sm4Key = new SecretKeySpec(keyData, "SM4");
        cipher.init(mode, sm4Key);
        return cipher;
    }


    //加密文件
    public static void encryptFile(String sourcePath, String targetPath){
        //加密文件
        try {
            Cipher cipher = generateCipher(Cipher.ENCRYPT_MODE, SM4Tools.keyData);
            CipherInputStream cipherInputStream = new CipherInputStream(new FileInputStream(sourcePath), cipher);
            FileUtil.writeFromStream(cipherInputStream, targetPath);
            IoUtil.close(cipherInputStream);
        } catch (InvalidKeyException | NoSuchPaddingException | NoSuchAlgorithmException | NoSuchProviderException |
                 FileNotFoundException e) {
            e.printStackTrace();
        }
    }


    /**
     * 解密文件
     *
     * @param sourcePath 待解密的文件路径
     * @param targetPath 解密后的文件路径
     */
    public static void decryptFile(String sourcePath, String targetPath) {
        System.out.println("==================开始解密========================");
        FileInputStream in =null;
        ByteArrayInputStream byteArrayInputStream =null;
        OutputStream out = null;
        CipherOutputStream cipherOutputStream=null;
        try {
            in = new FileInputStream(sourcePath);
            byte[] bytes = IoUtil.readBytes(in);
            byteArrayInputStream = IoUtil.toStream(bytes);

            Cipher cipher = generateCipher(Cipher.DECRYPT_MODE, SM4Tools.keyData);

            out = Files.newOutputStream(Paths.get(targetPath));
            cipherOutputStream = new CipherOutputStream(out, cipher);
            IoUtil.copy(byteArrayInputStream, cipherOutputStream);
        } catch (IOException | NoSuchPaddingException | InvalidKeyException | NoSuchAlgorithmException |
                 NoSuchProviderException e) {
            e.printStackTrace();
        } finally {
            IoUtil.close(cipherOutputStream);
            IoUtil.close(out);
            IoUtil.close(byteArrayInputStream);
            IoUtil.close(in);
        }
        System.out.println("==================解密完成========================");
    }

文件压缩

public class FileZip {



    /**
     * 压缩
     * @param zipFileName 压缩后的文件路径 F:\\javatest\\zip_test.zip
     * @param targetFile  需要压缩的文件 new File("F:\\javatest\\text")
     */
    public static void compression(String zipFileName,File targetFile) {
        System.out.println("正在压缩...");
        try {
            //要生成的压缩文件
            ZipOutputStream out = new ZipOutputStream(new FileOutputStream(zipFileName));
            BufferedOutputStream bos = new BufferedOutputStream(out);
            zip(out,targetFile,targetFile.getName(),bos);
            bos.close();
            out.close();
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        System.out.println("压缩完成!");
    }
    //zip
    private static void zip(ZipOutputStream zOut, File targetFile,
                            String name, BufferedOutputStream bos) throws IOException {

        //如果是目录
        if(targetFile.isDirectory()) {
            File[] files = targetFile.listFiles(); //获取子目录
            if(targetFile.length() == 0) {
                zOut.putNextEntry(new ZipEntry(name + "/")); //处理空目录 文件夹后面有个/
            }
            //如果文件夹不为空 递归处理子文件
            for(File f: files){
                //递归处理
                zip(zOut,f,name + "/" + f.getName(),bos);
            }

        }else { //如果不是目录

            zOut.putNextEntry(new ZipEntry(name));//处理文件 添加条目
            InputStream in = new FileInputStream(targetFile);
            BufferedInputStream bis = new BufferedInputStream(in);
            byte[] bytes = new byte[1024];
            int len = -1;
            while((len = bis.read(bytes)) != -1) {
                bos.write(bytes,0,len);
            }
            bis.close();
        }

    }

    /**
     * 解压
     * @param targetFileName 需要解压的文件路径
     * @param parent         解压到哪 的路径
     */
    public static Boolean decompression(String targetFileName,String parent) {
        System.out.println("正在解压...");
        try {
            //1.构建解压输出流
            ZipInputStream zIn = new ZipInputStream(Files.newInputStream(Paths.get(targetFileName)));
            ZipEntry entry = null;
            File file = null;
            //2.循环取值  有下一级 且为文件不是目录
            while((entry = zIn.getNextEntry()) !=null && !entry.isDirectory()){
                file = new File(parent,entry.getName()); //父目录+当前条目名字
                //如果文件不存在
                if(!file.exists()) {
                    new File(file.getParent()).mkdirs();//创建此文件的上级目录
                }
                //3.写文件
                OutputStream out = Files.newOutputStream(file.toPath());
                BufferedOutputStream bos = new BufferedOutputStream(out);
                byte[] bytes = new byte[1024];
                int len = -1;
                while((len = zIn.read(bytes)) != -1) {
                    bos.write(bytes,0,len);
                }
                bos.close();
                System.out.println(file.getAbsolutePath() + "解压成功!");
            }

            return true;
        } catch (IOException e) {
            e.printStackTrace();
            return false;
        }

    }
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值