text_blind_watermark/
utils.rs

1use rand::prelude::StdRng;
2use rand::{Rng, SeedableRng};
3
4pub fn str2bin(str1: &str) -> Vec<u8> {
5    // 从字符串得到二进制
6    let mut bin1 = Vec::with_capacity(str1.len() * 8);
7    for &byte in str1.as_bytes() {
8        for i in (0..8).rev() {
9            let bit = (byte >> i) & 1;
10            bin1.push(bit as u8);
11        }
12    }
13    return bin1;
14}
15
16pub fn bin2str(bin1: &[u8]) -> Result<String, &'static str> {
17    if bin1.len() % 8 != 0 {
18        return Err("len of input should be 8n");
19    }
20
21    let bytes: Vec<u8> = bin1
22        .chunks(8)
23        .map(|chunk| {
24            chunk.iter().enumerate().fold(0, |acc, (i, &bit)| {
25                // 确保bit要么是0,要么是1
26                if bit > 1 {
27                    return acc;
28                }
29                // 将8个比特组合成一个字节
30                acc | (bit << (7 - i))
31            })
32        })
33        .collect();
34
35    // 使用 String::from_utf8_lossy 来处理可能的无效UTF-8序列
36    Ok(String::from_utf8_lossy(&bytes).into_owned())
37}
38
39
40
41pub struct UtilWithCrypto {
42    seed: [u8; 32],
43}
44
45impl UtilWithCrypto {
46    pub fn new(pwd: &str) -> Self {
47        let mut seed: [u8; 32] = [0u8; 32];
48        let bytes = pwd.as_bytes();
49        let end = bytes.len().min(32);
50        seed[..end].copy_from_slice(&bytes[..end]);
51        Self { seed }
52    }
53
54    pub fn bytes2bin(&self, bytes1: &Vec<u8>) -> Vec<u8> {
55        // bytes 得到 二进制
56        let mut rng: StdRng = SeedableRng::from_seed(self.seed);
57
58        let mut bin1 = Vec::with_capacity(bytes1.len() * 8);
59        for byte in bytes1 {
60            let rand_num: u8 = rng.gen_range(0..=255);
61            let byte1 = byte ^ rand_num;
62            for i in (0..8).rev() {
63                let bit = (byte1 >> i) & 1;
64                bin1.push(bit as u8);
65            }
66        }
67        return bin1;
68    }
69
70
71    pub fn bin2bytes(&self, bin1: Vec<u8>) -> Vec<u8> {
72        let mut bin1 = bin1.clone();
73        // 补充零以使长度成为 8 的倍数
74        while bin1.len() % 8 != 0 {
75            bin1.push(0);
76        }
77
78
79        let mut rng: StdRng = SeedableRng::from_seed(self.seed);
80        let result_bytes: Vec<u8> = bin1
81            .chunks(8)
82            .map(|chunk| {
83                chunk.iter().enumerate().fold(0, |acc, (i, &bit)| {
84                    // 确保 bit 要么是 0,要么是 1
85                    if bit > 1 {
86                        return acc;
87                    }
88                    // 将 8 个比特组合成一个字节
89                    acc | (bit << (7 - i))
90                })
91            })
92            .map(|x| {
93                let rand_num: u8 = rng.gen_range(0..=255);
94                x ^ rand_num
95            })
96            .collect();
97
98        result_bytes
99    }
100}
101
102
103