serde2file
serialize some data to a file or deserialize a data from a file by
support encrypt/decrypt file
将struct序列化化存储为文件,或者从文件反序列化为struct
文件存储时支持加密存储
derive macro FileSerializeAndDeserialize Attributes(Optional):
- fileencrypt
- encrypt Data encryption method
- decrypt Data decryption method
- The above encryption and decryption methods must be set at the same time, otherwise encryption and decryption will not be performed.
- #[file
encrypt(encrypt="TestEncryptTool::encrypt",decrypt="TestEncryptTool::decrypt")]
dumpfilename
- Custom dump file name
- If not set ,the default dump file name is the full name of the current Struct.
- For example, the default dump file name corresponding to serde2file::test::TestData is serde2file-test-TestData
- #[dumpfilename = "test_data"]
派生宏FileSerializeAndDeserialize属性(可选)
- fileencrypt
- encrypt 数据加密方法
- decrypt 数据解密方法
- 以上加密和解密方法必须同时设置,否则不进行加解密。
- #[file
encrypt(encrypt="TestEncryptTool::encrypt",decrypt="TestEncryptTool::decrypt")]
dumpfilename
- 设置自定义的转储文件名称
- 自定义转储文件名称
- 默认为当前Struct的完整名称,
- 如serde2file::test::TestData对应的缺省转储文件名称为serde2file-test-TestData
- #[dumpfilename = "test_data"]
示例 / Example
```ignore
use serde::{Deserialize, Serialize};
use aesgcm::aead::{Aead, NewAead};
use aesgcm::{Aes256Gcm, Key, Nonce};
use serde2file::prelude::*;
[derive(Debug, Serialize, Deserialize, Default, PartialEq, Eq, FileSerializeAndDeserialize)]
[file_encrypt(encrypt="TestEncryptTool::encrypt",decrypt="TestEncryptTool::decrypt")]
[dumpfilename = "test_data"]
struct TestData {
id: String,
name: String,
}
/// a encryption and decryption tools
///
/// 自定义加密和解密工具
[allow(dead_code)]
struct TestEncryptTool;
/// some
impl TestEncryptTool {
pub fn getaeskeynonce() -> (String, String) {
(
"*)#@140600!$=^20230208)leb*$xz".into(),
"abc$hy%95599".into(),
)
}
pub fn encrypt(data: &str) -> DumpResult> {
let (keystr, noncestr) = Self::getaeskeynonce();
let key = Key::fromslice(keystr.asbytes());
let cipher = Aes256Gcm::new(key);
let nonce = Nonce::fromslice(noncestr.asbytes());
let cipherdata = cipher.encrypt(nonce, data.asbytes().asref()).unwrap();
Ok(cipherdata)
}
pub fn decrypt(data: Vec) -> DumpResult> {
let (keystr, noncestr) = Self::getaeskeynonce();
let key = Key::fromslice(keystr.asbytes());
let cipher = Aes256Gcm::new(key);
let nonce = Nonce::fromslice(noncestr.asbytes());
let plaindata = cipher.decrypt(nonce, data.asref()).unwrap();
Ok(plaindata)
}
}
cfg(test)
mod test {
use super::*;
/// Test serialization and encrypted storage to file
/// 测试序列化并加密存储到文件
#[test]
fn testserializetofile() {
let data = TestData {
id: "01".into(),
name: "hy".into(),
};
data.dumptofile("/tmp").unwrap();
}
/// Test deserialization from encrypted file
/// 测试从加密文件反序列化
#[test]
fn testdeserializefromfile() {
let data = TestData {
id: "01".into(),
name: "hy".into(),
};
let sdata = TestData::loadfromfile("/tmp").unwrap();
asserteq!(data, s_data)
}
}