Created
May 29, 2023 05:42
-
-
Save 641i130/953777c23348b9bc5c18f76f0701296b to your computer and use it in GitHub Desktop.
JSON Serialize Aes 128 Cfb Rust Example
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
[package] | |
name = "aes-json" | |
version = "0.1.0" | |
edition = "2021" | |
# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html | |
[dependencies] | |
aes = "0.8.2" | |
cfb-mode = "0.8.2" | |
serde = {version="1.0.163",features = ['derive']} | |
serde_json = {version = "1.0.96", features = ['std']} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
use aes::cipher::{AsyncStreamCipher, KeyIvInit}; | |
use serde::{Deserialize, Serialize}; | |
type Aes128CfbEnc = cfb_mode::Encryptor<aes::Aes128>; | |
#[derive(Serialize, Deserialize)] | |
struct MyData { | |
// Define your JSON structure here | |
// Example: | |
name: String, | |
age: u32, | |
// ... | |
} | |
macro_rules! print_valid_chars { | |
($slice:expr) => {{ | |
print!("{{{{"); | |
let mut valid_chars = String::new(); | |
for &byte in $slice { | |
if let Ok(chr) = std::str::from_utf8(&[byte]) { | |
if chr.is_ascii() && &byte >= &32 { | |
valid_chars.push_str(chr); | |
} | |
} else { | |
valid_chars.push_str("."); | |
} | |
} | |
println!("{}}}}}", valid_chars); | |
}}; | |
} | |
fn main() { | |
// Create an instance of your JSON object | |
let data: MyData = MyData { name: "Alice".to_string(), age: 30 }; | |
let plaintext: String = serde_json::to_string(&data).unwrap(); | |
dbg!(&plaintext); | |
// Crypto constants | |
let key: &[u8] = "0123456789012345".as_bytes(); | |
let iv: &[u8] = "0123456789012345".as_bytes(); | |
// Encrypt | |
let mut ciphertext = plaintext.as_bytes().to_vec(); | |
Aes128CfbEnc::new(key.into(), iv.into()).encrypt(&mut ciphertext); | |
print_valid_chars!(ciphertext.iter()); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment