use qfe::{
Frame,
QfeError,
establish_sqs_kem,
};
use std::error::Error;
fn main() -> Result<(), Box<dyn Error>> {
let current_date_str = "2025-04-06"; println!("--- QFE Comprehensive Example ({}) ---", current_date_str);
println!("\n[1] Initializing Frames and Establishing SQS...");
let alice_id = "Alice";
let bob_id = "Bob";
let mut frame_a = Frame::initialize(alice_id.to_string());
let mut frame_b = Frame::initialize(bob_id.to_string());
println!(" Initialized Frame for {} and {}", alice_id, bob_id);
establish_sqs_kem(&mut frame_a, &mut frame_b, "hello")
.map_err(|e| format!("SQS Establishment between {} and {} failed: {}", alice_id, bob_id, e))?;
println!(" SQS established successfully between {} and {}.", alice_id, bob_id);
assert!(frame_a.has_sqs() && frame_b.has_sqs());
println!("\n[2] Demonstrating AEAD Encryption/Decryption...");
let plaintext1 = b"Secret message protected by AEAD!";
let associated_data1 = Some(b"Context_ID_123" as &[u8]); println!(" {} wants to send: '{}'", alice_id, String::from_utf8_lossy(plaintext1));
println!(" Using Associated Data: '{}'", String::from_utf8_lossy(associated_data1.unwrap()));
let encrypted_msg = frame_a.encode_aead(plaintext1, associated_data1)
.map_err(|e| format!("{} failed to encode AEAD: {}", alice_id, e))?;
println!(" {} encoded message (Nonce: {:x?}, Ciphertext+Tag length: {} bytes)",
alice_id,
&encrypted_msg.nonce[..4], encrypted_msg.ciphertext.len()
);
let decoded_plaintext = frame_b.decode_aead(&encrypted_msg, associated_data1)
.map_err(|e| format!("{} failed to decode AEAD: {}", bob_id, e))?;
println!(" {} decoded message: '{}'", bob_id, String::from_utf8_lossy(&decoded_plaintext));
assert_eq!(plaintext1, decoded_plaintext.as_slice());
println!(" SUCCESS: AEAD decoded message matches original plaintext.");
assert!(frame_b.is_valid());
println!("\n[3] Error Example: Tampered AEAD Ciphertext...");
let plaintext3 = b"Another secret";
let mut encrypted_msg_tampered = frame_a.encode_aead(plaintext3, None)?;
println!(" {} encoded message: (Nonce: {:x?}, CT Len: {})", alice_id, &encrypted_msg_tampered.nonce[..4], encrypted_msg_tampered.ciphertext.len());
if !encrypted_msg_tampered.ciphertext.is_empty() {
encrypted_msg_tampered.ciphertext[0] ^= 0xFF; println!(" Ciphertext tampered!");
}
let decode_tampered_res = frame_b.decode_aead(&encrypted_msg_tampered, None);
assert!(decode_tampered_res.is_err());
if let Err(QfeError::DecodingFailed(msg)) = decode_tampered_res {
println!(" SUCCESS: {} correctly failed to decode tampered AEAD message: {}", bob_id, msg);
assert!(!frame_b.is_valid(), "Bob's frame should be invalid after failed AEAD decode");
println!(" {}'s frame validity: {}", bob_id, frame_b.is_valid());
} else {
panic!("Expected DecodingFailed error, got {:?}", decode_tampered_res.err());
}
println!("\n--- QFE Comprehensive Example Complete ---");
Ok(())
}