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);
}
相关推荐
Knight_AL9 分钟前
浅拷贝与深拷贝详解:概念、代码示例与后端应用场景
android·java·开发语言
枫叶丹411 分钟前
【Qt开发】输入类控件(六)-> QDial
开发语言·qt
思考的笛卡尔31 分钟前
Go语言实战:高并发服务器设计与实现
服务器·开发语言·golang
努力努力再努力wz42 分钟前
【C++进阶系列】:万字详解智能指针(附模拟实现的源码)
java·linux·c语言·开发语言·数据结构·c++·python
凤年徐1 小时前
【C++】string的模拟实现
c语言·开发语言·c++
敲代码的嘎仔1 小时前
JavaWeb零基础学习Day2——JS & Vue
java·开发语言·前端·javascript·数据结构·学习·算法
吃鱼吃鱼吃不动了1 小时前
什么是负载均衡?
开发语言·php
小蕾Java1 小时前
Python详细安装教程(附PyCharm使用)
开发语言·python·pycharm
weixin_307779131 小时前
AWS云上ClickHouse数据仓库部署方案详解
开发语言·clickhouse·自动化·云计算·aws
weixin_307779131 小时前
使用AWS IAM和Python自动化权限策略分析与导出
开发语言·python·自动化·云计算·aws