rust - 对文件进行zip压缩加密

本文提供了一种对文件进行zip压缩并加密的方法。

生成可见的加密密码

rust 复制代码
use rand::Rng;

const CHARSET: &[u8] = b"ABCDEFGHIJKLMNOPQRSTUVWXYZ\
abcdefghijklmnopqrstuvwxyz\
0123456789)(*&^%$#@!~";

pub fn random_string(len: usize) -> String {
    let mut rng = rand::thread_rng();
    let password: String = (0..len)
        .map(|_| {
            let idx = rng.gen_range(0..CHARSET.len());
            CHARSET[idx] as char
        })
        .collect();

    return password;
}

运行一次后得到一个随机密码

复制代码
random_string(16)

生成不可见的加密密码

为了密码的安全性,可以增加字符的范围。如下生成16个字符的随机密码。

rust 复制代码
pub fn get_random_key16() -> [u8; 16] {
    let mut arr = [0u8; 16];
    rand::thread_rng().try_fill(&mut arr[..]).expect("Ooops!");
    return arr;
}

压缩文件并加密

rust 复制代码
use anyhow::Result;
use std::io::Write;
use std::{fs, path::Path};
use zip::unstable::write::FileOptionsExt;
use zip::{write::FileOptions, CompressionMethod, ZipWriter};

/// 使用zip格式压缩文件
pub fn zip_file(key: Vec<u8>, src_path: &Path, dst_path: &Path) -> Result<()> {
    // 创建一个空的zip文件
    let file = fs::File::create(dst_path).unwrap();
    // 设置属性支持加密,使用默认压缩等级
    let mut zip = ZipWriter::new(file);
    let options = FileOptions::default()
        .compression_method(CompressionMethod::DEFLATE)
        .with_deprecated_encryption(&key);

    // 添加文件到zip包
    let src_file_name = src_path.file_name().unwrap();
    zip.start_file(src_file_name.to_os_string().to_str().unwrap(), options)
        .unwrap();
    let src_file_content = fs::read(src_path).unwrap();
    zip.write_all(&src_file_content).unwrap();
    zip.finish().unwrap();

    Ok(())
}

单元测试

rust 复制代码
use std::env;

#[test]
fn test_zip_file() {
    let src_file_path = env::current_dir().unwrap().join("tests/data.txt");
    let dst_file_path = env::current_dir().unwrap().join("tests/data.zip");
    let key = get_random_key16();
    let _ = zip_file(key.to_vec(), &src_file_path, &dst_file_path);
}
相关推荐
独自归家的兔8 小时前
Java性能优化实战:从基础调优到系统效率倍增 - 1
java·开发语言·性能优化
小π军8 小时前
C++ STL:array容器常见用法
开发语言·c++
156082072198 小时前
在QT下添加QWT6.1.4功能
开发语言·qt
minglie18 小时前
micropython_spiFlash_w25qxx
开发语言·python
源代码•宸8 小时前
Golang原理剖析(channel面试与分析)
开发语言·经验分享·后端·面试·golang·select·channel
H Corey8 小时前
Java--面向对象之继承与多态
java·开发语言·windows·学习·算法·intellij-idea
Gofarlic_OMS8 小时前
如何将MATLAB网络并发许可证闲置率降至10%以下
大数据·运维·服务器·开发语言·人工智能·matlab·制造
ejinxian8 小时前
2026 年 Java 开发计划-Oracle公布
java·开发语言·java 开发计划
Sylvia-girl8 小时前
Java之日志框架
java·开发语言
oioihoii9 小时前
QT跨平台一次编写,处处编译
开发语言·qt