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);
}
相关推荐
带带老表学爬虫1 分钟前
java数据类型转换和注释
java·开发语言
qianbo_insist4 分钟前
simple c++ 无锁队列
开发语言·c++
QMCY_jason10 分钟前
Ubuntu 安装RUST
linux·ubuntu·rust
BigYe程普14 分钟前
我开发了一个出海全栈SaaS工具,还写了一套全栈开发教程
开发语言·前端·chrome·chatgpt·reactjs·个人开发
彭于晏68916 分钟前
Android广播
android·java·开发语言
弱冠少年42 分钟前
websockets库使用(基于Python)
开发语言·python·numpy
长天一色42 分钟前
C语言日志类库 zlog 使用指南(第五章 配置文件)
c语言·开发语言
一般清意味……1 小时前
快速上手C语言【上】(非常详细!!!)
c语言·开发语言
卑微求AC1 小时前
(C语言贪吃蛇)16.贪吃蛇食物位置随机(完结撒花)
linux·c语言·开发语言·嵌入式·c语言贪吃蛇
技术无疆1 小时前
【Python】Streamlit:为数据科学与机器学习打造的简易应用框架
开发语言·人工智能·python·深度学习·神经网络·机器学习·数据挖掘