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

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

生成可见的加密密码

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个字符的随机密码。

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

压缩文件并加密

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(())
}

单元测试

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 - 文件进行zip压缩加密

    2024-03-21 10:06:02       46 阅读
  2. rust - 文件夹进行zip压缩加密

    2024-03-21 10:06:02       55 阅读
  3. rust 异步zip压缩

    2024-03-21 10:06:02       37 阅读
  4. C#使用SharpZipLib文件进行压缩和解压

    2024-03-21 10:06:02       49 阅读

最近更新

  1. docker php8.1+nginx base 镜像 dockerfile 配置

    2024-03-21 10:06:02       94 阅读
  2. Could not load dynamic library ‘cudart64_100.dll‘

    2024-03-21 10:06:02       100 阅读
  3. 在Django里面运行非项目文件

    2024-03-21 10:06:02       82 阅读
  4. Python语言-面向对象

    2024-03-21 10:06:02       91 阅读

热门阅读

  1. 小程序返回webview h5 不刷新问题

    2024-03-21 10:06:02       43 阅读
  2. Redis持久化策略

    2024-03-21 10:06:02       36 阅读
  3. 大数据开发(Hadoop面试真题)

    2024-03-21 10:06:02       37 阅读
  4. C++总结

    C++总结

    2024-03-21 10:06:02      37 阅读
  5. Oracle分析函数

    2024-03-21 10:06:02       42 阅读
  6. 卡牌游戏。

    2024-03-21 10:06:02       44 阅读
  7. MATLAB入门指南:从零开始进行数学建模竞赛

    2024-03-21 10:06:02       41 阅读
  8. 软件测试:LLVM中的Fuzz模糊测试框架——libFuzzer

    2024-03-21 10:06:02       44 阅读