Skip to main content

XChaChaKey

Struct XChaChaKey 

Source
pub struct XChaChaKey(/* private fields */);
Expand description

XChaCha20Poly1305 key (256 bits / 32 bytes)

Implementations§

Source§

impl XChaChaKey

Source

pub fn generate() -> Self

Generate a new random key

Examples found in repository?
examples/basic_usage.rs (line 35)
33fn xchacha_example() -> Result<()> {
34    // Generate a key and nonce
35    let key = XChaChaKey::generate();
36    let nonce = XChaChaNonce::generate();
37    
38    // Message to encrypt
39    let plaintext = b"Hello, World! This is a secret message.";
40    let aad = b"Additional authenticated data";
41    
42    println!("  Original message: {:?}", std::str::from_utf8(plaintext).unwrap());
43    println!("  Key size: {} bytes", key.as_bytes().len());
44    println!("  Nonce size: {} bytes", nonce.as_bytes().len());
45    
46    // Encrypt the message
47    let ciphertext = XChaChaCrypto::encrypt(&key, &nonce, plaintext, Some(aad))?;
48    println!("  Ciphertext size: {} bytes", ciphertext.len());
49    
50    // Decrypt the message
51    let decrypted = XChaChaCrypto::decrypt(&key, &nonce, &ciphertext, Some(aad))?;
52    println!("  Decrypted message: {:?}", std::str::from_utf8(&decrypted).unwrap());
53    
54    // Verify they match
55    assert_eq!(plaintext, &decrypted[..]);
56    println!("  ✓ Encryption/Decryption successful!");
57    
58    Ok(())
59}
More examples
Hide additional examples
examples/benchmark.rs (line 37)
36fn benchmark_xchacha() -> Result<()> {
37    let key = XChaChaKey::generate();
38    let nonce = XChaChaNonce::generate();
39    let plaintext = vec![0u8; MESSAGE_SIZE];
40    
41    // Benchmark encryption
42    let start = Instant::now();
43    let mut ciphertext = Vec::new();
44    for _ in 0..BENCHMARK_ITERATIONS {
45        ciphertext = XChaChaCrypto::encrypt(&key, &nonce, &plaintext, None)?;
46    }
47    let encryption_time = start.elapsed();
48    
49    // Benchmark decryption
50    let start = Instant::now();
51    for _ in 0..BENCHMARK_ITERATIONS {
52        let _decrypted = XChaChaCrypto::decrypt(&key, &nonce, &ciphertext, None)?;
53    }
54    let decryption_time = start.elapsed();
55    
56    let encryption_throughput = (BENCHMARK_ITERATIONS * MESSAGE_SIZE) as f64 / encryption_time.as_secs_f64() / 1_000_000.0;
57    let decryption_throughput = (BENCHMARK_ITERATIONS * MESSAGE_SIZE) as f64 / decryption_time.as_secs_f64() / 1_000_000.0;
58    
59    println!("  Encryption: {:.2} MB/s ({:.2} μs per operation)", 
60             encryption_throughput, 
61             encryption_time.as_micros() as f64 / BENCHMARK_ITERATIONS as f64);
62    println!("  Decryption: {:.2} MB/s ({:.2} μs per operation)", 
63             decryption_throughput, 
64             decryption_time.as_micros() as f64 / BENCHMARK_ITERATIONS as f64);
65    
66    Ok(())
67}
Source

pub fn from_bytes(bytes: &[u8]) -> Result<Self>

Create a key from raw bytes

Examples found in repository?
examples/benchmark.rs (line 115)
104fn benchmark_hybrid() -> Result<()> {
105    let plaintext = vec![0u8; MESSAGE_SIZE];
106    
107    // Benchmark full hybrid encryption
108    let start = Instant::now();
109    for _ in 0..BENCHMARK_ITERATIONS {
110        // Key establishment
111        let alice_keypair = KyberCrypto::generate_keypair();
112        let (shared_secret, _kyber_ciphertext) = KyberCrypto::encapsulate(&alice_keypair.public_key);
113        
114        // Data encryption
115        let xchacha_key = XChaChaKey::from_bytes(shared_secret.as_bytes())?;
116        let (_nonce, _ciphertext) = XChaChaCrypto::encrypt_with_random_nonce(
117            &xchacha_key,
118            &plaintext,
119            None,
120        )?;
121    }
122    let hybrid_time = start.elapsed();
123    
124    let hybrid_throughput = (BENCHMARK_ITERATIONS * MESSAGE_SIZE) as f64 / hybrid_time.as_secs_f64() / 1_000_000.0;
125    
126    println!("  Hybrid Encryption: {:.2} MB/s ({:.2} ms per operation)", 
127             hybrid_throughput, 
128             hybrid_time.as_millis() as f64 / BENCHMARK_ITERATIONS as f64);
129    
130    Ok(())
131}
More examples
Hide additional examples
examples/basic_usage.rs (line 102)
94fn hybrid_example() -> Result<()> {
95    println!("  Setting up hybrid encryption...");
96    
97    // Step 1: Key establishment with Kyber1024
98    let alice_keypair = KyberCrypto::generate_keypair();
99    let (shared_secret, kyber_ciphertext) = KyberCrypto::encapsulate(&alice_keypair.public_key);
100    
101    // Step 2: Use shared secret as XChaCha20Poly1305 key
102    let xchacha_key = XChaChaKey::from_bytes(shared_secret.as_bytes())?;
103    
104    // Step 3: Encrypt data with XChaCha20Poly1305
105    let plaintext = b"This is a secret message using hybrid post-quantum encryption!";
106    println!("  Message to encrypt: {:?}", std::str::from_utf8(plaintext).unwrap());
107    
108    let (nonce, ciphertext) = XChaChaCrypto::encrypt_with_random_nonce(
109        &xchacha_key,
110        plaintext,
111        None,
112    )?;
113    
114    println!("  Hybrid encryption complete!");
115    println!("  - Kyber ciphertext size: {} bytes", kyber_ciphertext.as_bytes().len());
116    println!("  - XChaCha nonce size: {} bytes", nonce.as_bytes().len());
117    println!("  - XChaCha ciphertext size: {} bytes", ciphertext.len());
118    
119    // Decryption process:
120    println!("  Decrypting...");
121    
122    // Step 1: Alice decapsulates the shared secret
123    let alice_shared_secret = KyberCrypto::decapsulate(&kyber_ciphertext, &alice_keypair.secret_key);
124    let alice_xchacha_key = XChaChaKey::from_bytes(alice_shared_secret.as_bytes())?;
125    
126    // Step 2: Decrypt the message
127    let decrypted = XChaChaCrypto::decrypt(&alice_xchacha_key, &nonce, &ciphertext, None)?;
128    
129    println!("  Decrypted message: {:?}", std::str::from_utf8(&decrypted).unwrap());
130    
131    // Verify they match
132    assert_eq!(plaintext, &decrypted[..]);
133    println!("  ✓ Hybrid encryption/decryption successful!");
134    
135    Ok(())
136}
Source

pub fn as_bytes(&self) -> &[u8] ⓘ

Get the raw key bytes

Examples found in repository?
examples/basic_usage.rs (line 43)
33fn xchacha_example() -> Result<()> {
34    // Generate a key and nonce
35    let key = XChaChaKey::generate();
36    let nonce = XChaChaNonce::generate();
37    
38    // Message to encrypt
39    let plaintext = b"Hello, World! This is a secret message.";
40    let aad = b"Additional authenticated data";
41    
42    println!("  Original message: {:?}", std::str::from_utf8(plaintext).unwrap());
43    println!("  Key size: {} bytes", key.as_bytes().len());
44    println!("  Nonce size: {} bytes", nonce.as_bytes().len());
45    
46    // Encrypt the message
47    let ciphertext = XChaChaCrypto::encrypt(&key, &nonce, plaintext, Some(aad))?;
48    println!("  Ciphertext size: {} bytes", ciphertext.len());
49    
50    // Decrypt the message
51    let decrypted = XChaChaCrypto::decrypt(&key, &nonce, &ciphertext, Some(aad))?;
52    println!("  Decrypted message: {:?}", std::str::from_utf8(&decrypted).unwrap());
53    
54    // Verify they match
55    assert_eq!(plaintext, &decrypted[..]);
56    println!("  ✓ Encryption/Decryption successful!");
57    
58    Ok(())
59}

Trait Implementations§

Source§

impl Clone for XChaChaKey

Source§

fn clone(&self) -> Self

Returns a duplicate of the value. Read more
1.0.0 (const: unstable) · Source§

fn clone_from(&mut self, source: &Self)

Performs copy-assignment from source. Read more
Source§

impl Zeroize for XChaChaKey

Source§

fn zeroize(&mut self)

Zero out this object from memory using Rust intrinsics which ensure the zeroization operation is not “optimized away” by the compiler.

Auto Trait Implementations§

Blanket Implementations§

Source§

impl<T> Any for T
where T: 'static + ?Sized,

Source§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
Source§

impl<T> Borrow<T> for T
where T: ?Sized,

Source§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
Source§

impl<T> BorrowMut<T> for T
where T: ?Sized,

Source§

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
Source§

impl<T> CloneToUninit for T
where T: Clone,

Source§

unsafe fn clone_to_uninit(&self, dest: *mut u8)

🔬This is a nightly-only experimental API. (clone_to_uninit)
Performs copy-assignment from self to dest. Read more
Source§

impl<T> From<T> for T

Source§

fn from(t: T) -> T

Returns the argument unchanged.

Source§

impl<T, U> Into<U> for T
where U: From<T>,

Source§

fn into(self) -> U

Calls U::from(self).

That is, this conversion is whatever the implementation of From<T> for U chooses to do.

Source§

impl<T> Same for T

Source§

type Output = T

Should always be Self
Source§

impl<T> ToOwned for T
where T: Clone,

Source§

type Owned = T

The resulting type after obtaining ownership.
Source§

fn to_owned(&self) -> T

Creates owned data from borrowed data, usually by cloning. Read more
Source§

fn clone_into(&self, target: &mut T)

Uses borrowed data to replace owned data, usually by cloning. Read more
Source§

impl<T, U> TryFrom<U> for T
where U: Into<T>,

Source§

type Error = !

The type returned in the event of a conversion error.
Source§

fn try_from(value: U) -> Result<T, !>

Performs the conversion.
Source§

impl<T, U> TryInto<U> for T
where U: TryFrom<T>,

Source§

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
Source§

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.