79 lines
2.5 KiB
Rust
79 lines
2.5 KiB
Rust
|
|
//! Age backend encryption example.
|
||
|
|
//!
|
||
|
|
//! Demonstrates basic encryption/decryption using the Age backend.
|
||
|
|
//!
|
||
|
|
//! # Usage
|
||
|
|
//!
|
||
|
|
//! ```bash
|
||
|
|
//! # Ensure Age key exists
|
||
|
|
//! age-keygen -o ~/.age/key.txt
|
||
|
|
//!
|
||
|
|
//! # Run example
|
||
|
|
//! cargo run --example age_backend --features age
|
||
|
|
//! ```
|
||
|
|
|
||
|
|
use encrypt::{decrypt, encrypt, BackendSpec};
|
||
|
|
|
||
|
|
fn main() -> Result<(), Box<dyn std::error::Error>> {
|
||
|
|
println!("=== Age Backend Encryption Example ===\n");
|
||
|
|
|
||
|
|
// Create Age backend spec with default key paths (~/.age/key.txt)
|
||
|
|
let spec = BackendSpec::age_default();
|
||
|
|
println!("Backend: {}", spec.backend_name());
|
||
|
|
println!("Using default key paths: ~/.age/key.txt\n");
|
||
|
|
|
||
|
|
// Plaintext secret
|
||
|
|
let secret = "my-super-secret-password-123!@#";
|
||
|
|
println!("Original secret: {}", secret);
|
||
|
|
|
||
|
|
// Encrypt
|
||
|
|
match encrypt(secret, &spec) {
|
||
|
|
Ok(ciphertext) => {
|
||
|
|
println!("✓ Encrypted successfully");
|
||
|
|
println!(
|
||
|
|
"Ciphertext (first 80 chars): {}...",
|
||
|
|
&ciphertext[..80.min(ciphertext.len())]
|
||
|
|
);
|
||
|
|
|
||
|
|
// Decrypt
|
||
|
|
match decrypt(&ciphertext, &spec) {
|
||
|
|
Ok(plaintext) => {
|
||
|
|
println!("✓ Decrypted successfully");
|
||
|
|
println!("Decrypted secret: {}", plaintext);
|
||
|
|
|
||
|
|
// Verify roundtrip
|
||
|
|
if plaintext == secret {
|
||
|
|
println!("\n✓ Roundtrip successful - plaintext matches!");
|
||
|
|
} else {
|
||
|
|
println!("\n✗ Roundtrip failed - plaintext mismatch!");
|
||
|
|
return Err("Roundtrip verification failed".into());
|
||
|
|
}
|
||
|
|
}
|
||
|
|
Err(e) => {
|
||
|
|
println!("✗ Decryption failed: {}", e);
|
||
|
|
return Err(e.into());
|
||
|
|
}
|
||
|
|
}
|
||
|
|
}
|
||
|
|
Err(e) => {
|
||
|
|
println!("✗ Encryption failed: {}", e);
|
||
|
|
println!("\nMake sure Age key exists:");
|
||
|
|
println!(" age-keygen -o ~/.age/key.txt");
|
||
|
|
return Err(e.into());
|
||
|
|
}
|
||
|
|
}
|
||
|
|
|
||
|
|
// Example 2: Custom key path
|
||
|
|
println!("\n=== Custom Key Path Example ===\n");
|
||
|
|
|
||
|
|
let custom_key_path = "/tmp/age-test-key.txt";
|
||
|
|
let spec_custom = BackendSpec::age(custom_key_path);
|
||
|
|
|
||
|
|
println!("Backend: {}", spec_custom.backend_name());
|
||
|
|
println!("Using custom key path: {}\n", custom_key_path);
|
||
|
|
println!("Note: Custom key path does not exist, so encryption would fail");
|
||
|
|
println!("To test, generate a key: age-keygen -o {}", custom_key_path);
|
||
|
|
|
||
|
|
Ok(())
|
||
|
|
}
|