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 小时前
静态交叉编译rust程序
开发语言·后端·rust
Johnny.Cheung1 小时前
非常好的Rust自动管理内存的例子
rust·内存管理·析构函数
读研的武1 小时前
DashGo零基础入门 纯Python的管理系统搭建
开发语言·python
Andy2 小时前
Python基础语法4
开发语言·python
但要及时清醒2 小时前
ArrayList和LinkedList
java·开发语言
孚亭2 小时前
Swift添加字体到项目中
开发语言·ios·swift
hweiyu002 小时前
Go、DevOps运维开发实战(视频教程)
开发语言·golang·运维开发
mm-q29152227292 小时前
Python+Requests零基础系统掌握接口自动化测试
开发语言·python
星星火柴9363 小时前
笔记 | C++面向对象高级开发
开发语言·c++·笔记·学习