### ChaCha20 Encryption and Decryption Example (Rust) Source: https://docs.rs/chacha20/latest/chacha20/index_search=u32+-%3E+bool Demonstrates how to use the ChaCha20 cipher for both encryption and decryption. It initializes the cipher with a key and nonce, applies the keystream to plaintext to get ciphertext, and then applies it again to decrypt. It also shows how to use the cipher with streaming messages. ```rust use chacha20::ChaCha20; // Import relevant traits use chacha20::cipher::{KeyIvInit, StreamCipher, StreamCipherSeek}; use hex_literal::hex; let key = [0x42; 32]; let nonce = [0x24; 12]; let plaintext = hex!("00010203 04050607 08090A0B 0C0D0E0F"); let ciphertext = hex!("e405626e 4f1236b3 670ee428 332ea20e"); // Key and IV must be references to the `GenericArray` type. // Here we use the `Into` trait to convert arrays into it. let mut cipher = ChaCha20::new(&key.into(), &nonce.into()); let mut buffer = plaintext.clone(); // apply keystream (encrypt) cipher.apply_keystream(&mut buffer); assert_eq!(buffer, ciphertext); let ciphertext = buffer.clone(); // ChaCha ciphers support seeking cipher.seek(0u32); // decrypt ciphertext by applying keystream again cipher.apply_keystream(&mut buffer); assert_eq!(buffer, plaintext); // stream ciphers can be used with streaming messages cipher.seek(0u32); for chunk in buffer.chunks_mut(3) { cipher.apply_keystream(chunk); } assert_eq!(buffer, ciphertext); ``` -------------------------------- ### Key and IV Initialization for StreamCipherCoreWrapper - Rust Source: https://docs.rs/chacha20/latest/chacha20/type.XChaCha20_search= Illustrates initializing a StreamCipherCoreWrapper with both a key and an initialization vector (IV). This is crucial for ciphers that require both to start the encryption or decryption process. ```rust impl KeyIvInit for StreamCipherCoreWrapper where T: KeyIvInit + BlockSizeUser, ::BlockSize: IsLess, B0>, B0>, B0>, B0>, B0>, B0>, B0>, B0>>, <::BlockSize as IsLess, B0>, B0>, B0>, B0>, B0>, B0>, B0>, B0>>>::Output: NonZero, { // ... implementation for key and IV initialization } ``` -------------------------------- ### ChaCha20 Test Vector Example in Rust Source: https://docs.rs/chacha20/latest/src/chacha20/xchacha.rs_search=Option%3CT%3E%2C+%28T+-%3E+U%29+-%3E+Option%3CU%3E Provides a unit test for the ChaCha20 implementation using a specific test vector. It defines constant key, input, and expected output arrays, then calls the hchacha function and asserts that the actual output matches the expected output. This test is crucial for verifying the correctness of the ChaCha20 algorithm implementation. It relies on the `hex_literal` crate for easy hex string parsing and the `generic_array` crate for handling fixed-size arrays. ```rust #[cfg(test)] mod hchacha20_tests { use super::*; use hex_literal::hex; #[test] fn test_vector() { const KEY: [u8; 32] = hex!( "000102030405060708090a0b0c0d0e0f" "101112131415161718191a1b1c1d1e1f" ); const INPUT: [u8; 16] = hex!("000000090000004a0000000031415927"); const OUTPUT: [u8; 32] = hex!( "82413b4227b27bfed30e42508a877d73" "a0f9e4d58a74a853c12ec41326d3ecdc" ); let actual = hchacha::( GenericArray::from_slice(&KEY), &GenericArray::from_slice(&INPUT), ); assert_eq!(actual.as_slice(), &OUTPUT); } } ``` -------------------------------- ### XChaChaCore Initialization and Properties Source: https://docs.rs/chacha20/latest/chacha20/struct.XChaChaCore Provides details on creating an XChaChaCore instance and its inherent properties like block size, key size, and IV size. ```APIDOC ## XChaChaCore ### Description The XChaCha core function. ### Key Size - **KeySize** (UInt, B0>, B0>, B0>, B0>, B0>) - Type alias for key size in bytes. - **key_size()** -> usize - Returns the key size in bytes. ### Block Size - **BlockSize** (UInt, B0>, B0>, B0>, B0>, B0>, B0>) - Type alias for block size in bytes. - **block_size()** -> usize - Returns the block size in bytes. ### IV Size - **IvSize** (UInt, B1>, B0>, B0>, B0>) - Type alias for initialization vector size in bytes. - **iv_size()** -> usize - Returns the IV size in bytes. ### Initialization - **new(key: &Key, iv: &XNonce)** -> Self - Creates a new XChaChaCore instance from a fixed-length key and nonce. - **new_from_slices(key: &[u8], iv: &[u8])** -> Result - Creates a new XChaChaCore instance from variable-length key and nonce slices. ``` -------------------------------- ### Get Core Reference - Rust Source: https://docs.rs/chacha20/latest/chacha20/type.ChaCha12_search=std%3A%3Avec Provides a method to get a reference to the core type within the StreamCipherCoreWrapper. This is a common pattern for accessing underlying cryptographic primitives in Rust. ```rust pub fn get_core(&self) -> &T ``` -------------------------------- ### StreamCipherCoreWrapper KeyInit Implementation Source: https://docs.rs/chacha20/latest/chacha20/type.ChaCha20_search=u32+-%3E+bool Demonstrates the `KeyInit` trait implementation for initializing the `StreamCipherCoreWrapper` with a key. It provides methods for creating a new cipher instance from a fixed-size key or a byte slice. ```rust fn new( key: &GenericArray as KeySizeUser>::KeySize>, ) -> StreamCipherCoreWrapper; ``` ```rust fn new_from_slice(key: &[u8]) -> Result; ``` -------------------------------- ### XChaChaCore Key and IV Initialization in Rust Source: https://docs.rs/chacha20/latest/chacha20/struct.XChaChaCore_search= Provides methods for initializing the XChaChaCore cipher with a key and nonce. Supports initialization from fixed-length key/nonce or slices, with error handling for invalid lengths. ```rust fn new(key: &Key, iv: &XNonce) -> Self fn new_from_slices(key: &[u8], iv: &[u8]) -> Result ``` -------------------------------- ### Get Core Reference for StreamCipherCoreWrapper in Rust Source: https://docs.rs/chacha20/latest/chacha20/type.ChaCha20Legacy_search=Option%3CT%3E%2C+%28T+-%3E+U%29+-%3E+Option%3CU%3E Provides a method to get an immutable reference to the underlying core type within a StreamCipherCoreWrapper. This allows access to the core's methods and data without consuming the wrapper. ```rust pub fn get_core(&self) -> &T ``` -------------------------------- ### Seek Keystream Position for StreamCipherCoreWrapper in Rust Source: https://docs.rs/chacha20/latest/chacha20/type.ChaCha20Legacy_search=u32+-%3E+bool Provides functionality to get and set the current position within the keystream for StreamCipherCoreWrapper. Supports safe (try_*) and unsafe versions of seeking and getting the position. Requires T to implement StreamCipherSeekCore. ```rust impl StreamCipherSeek for StreamCipherCoreWrapper where T: StreamCipherSeekCore, ::BlockSize: IsLess, B0>, B0>, B0>, B0>, B0>, B0>, B0>, B0>>, <::BlockSize as IsLess, B0>, B0>, B0>, B0>, B0>, B0>, B0>, B0>>>::Output: NonZero, { fn try_current_pos(&self) -> Result where SN: SeekNum, { // Implementation details unimplemented!(); } fn try_seek(&mut self, new_pos: SN) -> Result<(), StreamCipherError> where SN: SeekNum, { // Implementation details unimplemented!(); } fn current_pos(&self) -> SN where SN: SeekNum, { // Implementation details unimplemented!(); } fn seek(&mut self, pos: SN) where SN: SeekNum, { // Implementation details unimplemented!(); } } ``` -------------------------------- ### XChaChaCore Key Initialization Source: https://docs.rs/chacha20/latest/chacha20/struct.XChaChaCore_search=std%3A%3Avec Implements the KeyIvInit trait for XChaChaCore, providing methods to create a new XChaChaCore instance. `new` takes a fixed-length key and nonce, while `new_from_slices` accepts variable-length byte slices and returns a Result. ```rust impl KeyIvInit for XChaChaCore { fn new(key: &Key, iv: &XNonce) -> Self; fn new_from_slices(key: &[u8], iv: &[u8]) -> Result; } ``` -------------------------------- ### ChaChaCore Key Initialization Source: https://docs.rs/chacha20/latest/chacha20/struct.ChaChaCore_search= Enables the initialization of ChaChaCore with a key and initialization vector. It provides methods to create a new instance from fixed-size key and nonce, or from byte slices. ```Rust fn new(key: &Key, iv: &Nonce) -> Self> fn new_from_slices(key: &[u8], iv: &[u8]) -> Result ``` -------------------------------- ### Seek Stream Position with StreamCipherSeek Source: https://docs.rs/chacha20/latest/chacha20/type.ChaCha20Legacy_search=std%3A%3Avec Provides functionality to get and set the current position within the keystream using the StreamCipherSeek trait. It supports trying to get or set the position, returning Results to handle potential errors like overflow or stream cipher errors. Generic types are used for seek position. ```rust impl StreamCipherSeek for StreamCipherCoreWrapper where T: StreamCipherSeekCore, { fn try_current_pos(&self) -> Result where SN: SeekNum, { // Implementation details... unimplemented!() } fn try_seek(&mut self, new_pos: SN) -> Result<(), StreamCipherError> where SN: SeekNum, { // Implementation details... unimplemented!() } fn current_pos(&self) -> SN where SN: SeekNum, { // Implementation details... unimplemented!() } fn seek(&mut self, pos: SN) where SN: SeekNum, { // Implementation details... unimplemented!() } } ``` -------------------------------- ### Stream Cipher Seeking Source: https://docs.rs/chacha20/latest/chacha20/type.ChaCha20Legacy_search=std%3A%3Avec Provides functionalities to get and set the current position within the keystream. ```APIDOC ## Stream Cipher Seeking ### Description These methods allow for querying and manipulating the current position within the generated keystream. ### Methods - **`try_current_pos(&self) -> Result`**: Try to get the current keystream position. - **`try_seek(&mut self, new_pos: SN) -> Result<(), StreamCipherError>`**: Try to seek to the given position. - **`current_pos(&self) -> T`**: Get the current keystream position (non-failable). - **`seek(&mut self, pos: T)`**: Seek to the given position (non-failable). ### Endpoint N/A (Method Calls) ### Parameters - **`SN`** (Generic Type `SeekNum`): Type parameter for position, must implement `SeekNum`. - **`new_pos`** (`SN`): The new position to seek to. - **`T`** (Generic Type `SeekNum`): Type parameter for position, must implement `SeekNum`. - **`pos`** (`T`): The position to seek to. ### Request Example ```rust // Example for try_current_pos match cipher.try_current_pos::() { Ok(pos) => println!("Current position: {}", pos), Err(e) => eprintln!("Error getting position: {:?}", e), } // Example for try_seek let new_position = 1024u64; match cipher.try_seek(new_position) { Ok(_) => println!("Seek successful."), Err(e) => eprintln!("Error seeking: {:?}", e), } ``` ### Response #### Success Response - **`SN` or `T`**: The current keystream position. - **`()`**: Indicates successful seek operation. - **`Result`**: Returns Ok(position) on success or an OverflowError on failure for `try_current_pos`. - **`Result<(), StreamCipherError>`**: Returns Ok(()) on success or a StreamCipherError on failure for `try_seek`. ``` -------------------------------- ### ChaChaCore Key and IV Initialization in Rust Source: https://docs.rs/chacha20/latest/chacha20/struct.ChaChaCore_search=Option%3CT%3E%2C+%28T+-%3E+U%29+-%3E+Option%3CU%3E Shows how to initialize the ChaChaCore with a key and initialization vector. The KeyIvInit trait provides methods to create a new ChaChaCore instance from fixed-size keys/IVs or slices, handling potential length errors. ```rust fn new(key: &Key, iv: &Nonce) -> Self; fn new_from_slices(key: &[u8], iv: &[u8]) -> Result ``` -------------------------------- ### Key Size API Source: https://docs.rs/chacha20/latest/chacha20/type.XChaCha8 Provides methods to get the key size of the stream cipher. ```APIDOC ## Key Size ### Description Provides methods to retrieve the key size of the stream cipher in bytes. ### Methods #### `key_size()` - **Description**: Returns the key size in bytes. - **Method**: `GET` - **Endpoint**: `/websites/rs_chacha20/key_size` #### `KeySizeUser` Trait - **Description**: Defines the key size for a stream cipher. - **Type**: `KeySize` (type alias for the key size) - **Endpoint**: Not directly accessible as an endpoint, but a trait implementation detail. ### Request Example ```json { "example": "No request body needed for key size retrieval." } ``` ### Response Example (Success) ```json { "key_size": 32 } ``` ``` -------------------------------- ### StreamCipherCoreWrapper Seeking Source: https://docs.rs/chacha20/latest/chacha20/type.XChaCha20_search=u32+-%3E+bool Provides functionality to get the current position within the keystream and to seek to a specific position. ```APIDOC ## StreamCipherCoreWrapper Seeking ### `try_current_pos` Asynchronously attempt to retrieve the current position within the keystream. This operation can fail. #### Type Parameters - **SN**: The type used to represent the seek position, must implement `SeekNum`. #### Returns - `Result` - The current position on success, or an `OverflowError` if the position cannot be represented by `SN`. ### `try_seek` Asynchronously attempt to seek to a new position within the keystream. This operation can fail. #### Type Parameters - **SN**: The type used to represent the seek position, must implement `SeekNum`. #### Parameters - **new_pos** (`SN`) - The desired new position in the keystream. #### Returns - `Result<(), StreamCipherError>` - Ok if the seek operation is successful, or a `StreamCipherError` on failure. ### `current_pos` Synchronously retrieve the current position within the keystream. #### Type Parameters - **T**: The type used to represent the seek position, must implement `SeekNum`. #### Returns - `T` - The current position in the keystream. ### `seek` Synchronously seek to a new position within the keystream. #### Type Parameters - **T**: The type used to represent the seek position, must implement `SeekNum`. #### Parameters - **pos** (`T`) - The desired new position in the keystream. ``` -------------------------------- ### Initialization Source: https://docs.rs/chacha20/latest/chacha20/type.XChaCha20 Provides methods for initializing the ChaCha20 stream cipher with a key and nonce. ```APIDOC ## POST /websites/rs_chacha20/new ### Description Creates a new ChaCha20 cipher instance using a fixed-length key and nonce. ### Method POST ### Endpoint /websites/rs_chacha20/new ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body - **key** (GenericArray) - Required - The encryption key. - **iv** (GenericArray) - Required - The initialization vector (nonce). ### Request Example ```json { "key": "...", "iv": "..." } ``` ### Response #### Success Response (200) - **StreamCipherCoreWrapper** - The initialized ChaCha20 cipher instance. #### Response Example ```json { "cipher": "..." } ``` ## POST /websites/rs_chacha20/new_from_slices ### Description Creates a new ChaCha20 cipher instance from byte slices for the key and nonce. This method returns an error if the lengths are invalid. ### Method POST ### Endpoint /websites/rs_chacha20/new_from_slices ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body - **key** (slice) - Required - The encryption key as a byte slice. - **iv** (slice) - Required - The initialization vector (nonce) as a byte slice. ### Request Example ```json { "key": [0, 1, 2, 3, ...], "iv": [0, 1, 2, 3, ...] } ``` ### Response #### Success Response (200) - **Result** - Ok containing the cipher instance or Err with an InvalidLength error. #### Response Example ```json { "result": { "ok": { "cipher": "..." } } } ``` ``` -------------------------------- ### KeyIvInit Implementation for StreamCipherCoreWrapper Source: https://docs.rs/chacha20/latest/chacha20/type.XChaCha20 Allows initialization of the XChaCha20 cipher with both a key and an initialization vector (IV). This implementation builds upon the KeyInit trait. ```rust impl where T: KeyIvInit + BlockSizeUser, ::BlockSize: IsLess, B0>, B0>, B0>, B0>, B0>, B0>, B0>, B0>>, <::BlockSize as IsLess, B0>, B0>, B0>, B0>, B0>, B0>, B0>, B0>>>::Output: NonZero, { // ... methods for key and IV initialization } ``` -------------------------------- ### Stream Cipher Seek Source: https://docs.rs/chacha20/latest/chacha20/type.ChaCha20Legacy Provides functionality to get the current position or seek to a new position within the keystream. ```APIDOC ## Stream Cipher Seek ### Description Provides functionality to get the current position or seek to a new position within the keystream. ### Method GET / POST ### Endpoint /websites/rs_chacha20/seek ### Parameters #### Path Parameters - **T** (Type Parameter) - Required - Specifies the type parameter for the stream cipher. #### Query Parameters (for GET) - **SN** (Type Parameter) - Required - The type of the seek number. #### Request Body (for POST) - **new_pos** (SN) - Required - The new position to seek to. ### Request Example (GET) ``` GET /websites/rs_chacha20/seek?SN=u64 ``` ### Request Example (POST) ```json { "new_pos": "1024" } ``` ### Response #### Success Response (200) - **current_pos** (T) - The current keystream position. - **Result** (Result<(), StreamCipherError>) - Indicates success or failure of the seek operation. #### Response Example ```json { "current_pos": "512" } ``` ```json { "Ok": null } ``` ``` -------------------------------- ### KeyInit Implementation for StreamCipherCoreWrapper in Rust Source: https://docs.rs/chacha20/latest/chacha20/type.ChaCha20_search=std%3A%3Avec Implements the `KeyInit` trait for `StreamCipherCoreWrapper`. This provides methods to initialize the cipher with a fixed-size key (`new`) or a variable-length slice (`new_from_slice`), handling potential length errors. ```rust fn new( key: &GenericArray as KeySizeUser>::KeySize>, ) -> StreamCipherCoreWrapper ``` ```rust fn new_from_slice(key: &[u8]) -> Result ``` -------------------------------- ### Get Key Size for StreamCipherCoreWrapper Source: https://docs.rs/chacha20/latest/chacha20/type.ChaCha20Legacy_search=std%3A%3Avec Retrieves the key size in bytes for a StreamCipherCoreWrapper. This function is part of the KeySizeUser trait implementation. ```rust impl KeySizeUser for StreamCipherCoreWrapper where T: KeySizeUser + BlockSizeUser, { type KeySize = ::KeySize; fn key_size() -> usize { ::key_size() } } ``` -------------------------------- ### StreamCipherCoreWrapper Initialization Source: https://docs.rs/chacha20/latest/chacha20/type.XChaCha20_search=std%3A%3Avec Provides methods for initializing the ChaCha20 stream cipher wrapper with different key and nonce configurations. ```APIDOC ## ChaCha20 Stream Cipher Initialization ### `fn new(key: &GenericArray as KeySizeUser>::KeySize>, iv: &GenericArray as IvSizeUser>::IvSize>) -> StreamCipherCoreWrapper` #### Description Creates a new `StreamCipherCoreWrapper` instance using a fixed-length key and nonce. #### Parameters - `key` (GenericArray): The encryption key. - `iv` (GenericArray): The initialization vector (nonce). #### Return Value A new `StreamCipherCoreWrapper` instance. --- ### `fn new_from_slices(key: &[u8], iv: &[u8]) -> Result` #### Description Creates a new `StreamCipherCoreWrapper` instance from byte slices for the key and nonce. This method allows for variable-length inputs and returns an error if the lengths are invalid. #### Parameters - `key` (&[u8]): The encryption key as a byte slice. - `iv` (&[u8]): The initialization vector (nonce) as a byte slice. #### Return Value A `Result` containing either a new `StreamCipherCoreWrapper` instance on success or an `InvalidLength` error if the key or nonce has an incorrect size. ``` -------------------------------- ### Get Key Size in Bytes Source: https://docs.rs/chacha20/latest/chacha20/type.ChaCha12_search= Retrieves the key size in bytes for the stream cipher. This is a fundamental property of the cipher's configuration. ```rust fn key_size() -> usize ``` -------------------------------- ### Get Current Position - Rust Source: https://docs.rs/chacha20/latest/chacha20/type.ChaCha20_search= Retrieves the current position within the keystream. This is useful for tracking progress or for resuming operations later. ```Rust fn current_pos(&self) -> T where T: SeekNum ``` -------------------------------- ### Initialize ChaCha20 with Key in Rust Source: https://docs.rs/chacha20/latest/chacha20/type.ChaCha20 Demonstrates how to initialize a `StreamCipherCoreWrapper` (which represents ChaCha20) using a fixed-size key. This is part of the `KeyInit` trait implementation. ```rust pub fn new( key: &GenericArray as KeySizeUser>::KeySize>, ) -> StreamCipherCoreWrapper ``` -------------------------------- ### Ordering Implementation Source: https://docs.rs/chacha20/latest/chacha20/type.Nonce Details on how GenericArray instances can be compared. ```APIDOC ### impl Ord for GenericArray ### Description Provides total ordering for `GenericArray` instances if the element type `T` supports ordering. ### Methods #### `fn cmp(&self, other: &GenericArray) -> Ordering` Compares `self` with `other` and returns an `Ordering`. - **other** (&GenericArray) - The other array to compare against. - Returns `Ordering::Less`, `Ordering::Equal`, or `Ordering::Greater`. ``` ```APIDOC #### `fn max(self, other: Self) -> Self` Compares two arrays and returns the greater one. - **other** (Self) - The other array to compare. - Returns the maximum of the two arrays. ``` ```APIDOC #### `fn min(self, other: Self) -> Self` Compares two arrays and returns the smaller one. - **other** (Self) - The other array to compare. - Returns the minimum of the two arrays. ``` ```APIDOC #### `fn clamp(self, min: Self, max: Self) -> Self` Restricts a value to be within a specified interval (inclusive). - **min** (Self) - The minimum allowed value. - **max** (Self) - The maximum allowed value. - Returns the clamped value. ``` -------------------------------- ### Get Key Size for StreamCipherCoreWrapper Source: https://docs.rs/chacha20/latest/chacha20/type.XChaCha12 Retrieves the key size in bytes for the StreamCipherCoreWrapper. This function relies on the KeySizeUser trait implemented by the generic type T. ```rust impl KeySizeUser for StreamCipherCoreWrapper where T: KeySizeUser + BlockSizeUser, { type KeySize = ::KeySize; } fn key_size() -> usize { // Implementation details would be here unimplemented!() } ``` -------------------------------- ### Get Key Size (Rust) Source: https://docs.rs/chacha20/latest/chacha20/type.ChaCha8_search= Returns the size of the key in bytes for the stream cipher. This is a fundamental property of the cipher's configuration. ```Rust /// Return key size in bytes. fn key_size() -> usize ``` -------------------------------- ### ChaCha20LegacyCore Initialization Methods - Rust Source: https://docs.rs/chacha20/latest/chacha20/struct.ChaCha20LegacyCore Demonstrates how to initialize a ChaCha20LegacyCore instance. It includes methods to create a new cipher with a fixed-length key and nonce, or from byte slices. ```Rust fn new(key: &Key, iv: &LegacyNonce) -> Self; fn new_from_slices(key: &[u8], iv: &[u8]) -> Result; ``` -------------------------------- ### Get Key Size for StreamCipherCoreWrapper Source: https://docs.rs/chacha20/latest/chacha20/type.ChaCha20 Retrieves the key size in bytes for the StreamCipherCoreWrapper. This implementation requires the generic type T to implement KeySizeUser and BlockSizeUser traits. ```Rust impl KeySizeUser for StreamCipherCoreWrapper where T: KeySizeUser + BlockSizeUser, ::BlockSize: IsLess, B0>, B0>, B0>, B0>, B0>, B0>, B0>, B0>>, <::BlockSize as IsLess, B0>, B0>, B0>, B0>, B0>, B0>, B0>, B0>>>::Output: NonZero, { type KeySize = ::KeySize; fn key_size() -> usize { ::key_size() } } ``` -------------------------------- ### StreamCipherCoreWrapper KeyIvInit Implementation Source: https://docs.rs/chacha20/latest/chacha20/type.ChaCha20_search=u32+-%3E+bool Illustrates the `KeyIvInit` trait implementation, allowing initialization of the `StreamCipherCoreWrapper` with both a key and an initialization vector (IV). Methods for fixed-length and variable-length inputs are provided. ```rust fn new( key: &GenericArray as KeySizeUser>::KeySize>, iv: &GenericArray as IvSizeUser>::IvSize>, ) -> StreamCipherCoreWrapper; ``` ```rust fn new_from_slices(key: &[u8], iv: &[u8]) -> Result; ``` -------------------------------- ### KeyInit Trait Implementation for StreamCipherCoreWrapper in Rust Source: https://docs.rs/chacha20/latest/chacha20/type.XChaCha12 Shows the KeyInit trait implementation for StreamCipherCoreWrapper. This enables the initialization of the cipher wrapper using a fixed-size key or a key provided as a slice. It includes methods for creating a new instance from a key. ```rust impl KeyInit for StreamCipherCoreWrapper where T: KeyInit + BlockSizeUser, ::BlockSize: IsLess, B0>, B0>, B0>, B0>, B0>, B0>, B0>, B0>>, <::BlockSize as IsLess, B0>, B0>, B0>, B0>, B0>, B0>, B0>, B0>>>::Output: NonZero { fn new( key: &GenericArray as KeySizeUser>::KeySize>, ) -> StreamCipherCoreWrapper fn new_from_slice(key: &[u8]) -> Result } ``` -------------------------------- ### Seek Keystream Position Source: https://docs.rs/chacha20/latest/chacha20/type.ChaCha12_search= Provides functionality to seek to a specific position within the keystream. This involves methods for both trying to get the current position and setting a new position. ```rust fn try_current_pos(&self) -> Result ``` ```rust fn try_seek(&mut self, new_pos: SN) -> Result<(), StreamCipherError> ``` ```rust fn current_pos(&self) -> T ``` ```rust fn seek(&mut self, pos: T) ``` -------------------------------- ### ChaCha12 Initialization and Core Source: https://docs.rs/chacha20/latest/chacha20/type.ChaCha12_search= This section covers the initialization of the ChaCha12 cipher using keys and nonces, and provides methods to access and manage the underlying cipher core. ```APIDOC ## ChaCha12 Stream Cipher ### Description ChaCha12 is a stream cipher that uses a reduced-round variant of the ChaCha20 algorithm, employing 12 rounds. ### Type Alias ```rust pub type ChaCha12 = StreamCipherCoreWrapper>; ``` ### Aliased Type ```rust pub struct ChaCha12 { /* private fields */ } ``` ## Implementations for StreamCipherCoreWrapper ### `get_core()` - **Description**: Returns a reference to the internal cipher core. - **Method**: GET - **Endpoint**: N/A (Method on a struct instance) - **Parameters**: None ### `from_core(core: T)` - **Description**: Creates a `StreamCipherCoreWrapper` from an existing core type `T`. - **Method**: POST - **Endpoint**: N/A (Method on a struct instance) - **Parameters**: - `core` (T) - Required - The cipher core to wrap. ### `new(key: &GenericArray)` (KeyInit) - **Description**: Initializes the cipher with a fixed-size key. - **Method**: POST - **Endpoint**: N/A (Associated function) - **Parameters**: - `key` (GenericArray) - Required - The encryption key. - **Request Body**: N/A (Key is a parameter) ### `new_from_slice(key: &[u8])` (KeyInit) - **Description**: Initializes the cipher with a variable-length key slice. - **Method**: POST - **Endpoint**: N/A (Associated function) - **Parameters**: - `key` (slice of u8) - Required - The encryption key slice. - **Response**: `Result` - The initialized cipher or an error if the key length is invalid. ### `new(key: &GenericArray, iv: &GenericArray)` (KeyIvInit) - **Description**: Initializes the cipher with a fixed-size key and initialization vector (nonce). - **Method**: POST - **Endpoint**: N/A (Associated function) - **Parameters**: - `key` (GenericArray) - Required - The encryption key. - `iv` (GenericArray) - Required - The initialization vector (nonce). ### `new_from_slices(key: &[u8], iv: &[u8])` (KeyIvInit) - **Description**: Initializes the cipher with variable-length key and nonce slices. - **Method**: POST - **Endpoint**: N/A (Associated function) - **Parameters**: - `key` (slice of u8) - Required - The encryption key slice. - `iv` (slice of u8) - Required - The initialization vector (nonce) slice. - **Response**: `Result` - The initialized cipher or an error if lengths are invalid. ### `iv_size()` - **Description**: Returns the size of the initialization vector in bytes. - **Method**: GET - **Endpoint**: N/A (Associated function) - **Parameters**: None - **Response**: `usize` - The IV size. ### Trait Implementations - **Clone**: Allows creating copies of the cipher instance. - **Default**: Provides a default initialization for the cipher. - **Drop**: Handles the cleanup of the cipher instance (available with `zeroize` feature). ``` -------------------------------- ### ChaCha Core Initialization (Rust) Source: https://docs.rs/chacha20/latest/src/chacha20/lib.rs_search= Initializes the ChaCha core state with a given key and nonce. It sets up the initial state array based on constants and the provided key/nonce, handling different CPU target features for potential optimizations. ```rust impl KeyIvInit for ChaChaCore { #[inline] fn new(key: &Key, iv: &Nonce) -> Self { let mut state = [0u32; STATE_WORDS]; state[0..4].copy_from_slice(&CONSTANTS); let key_chunks = key.chunks_exact(4); for (val, chunk) in state[4..12].iter_mut().zip(key_chunks) { *val = u32::from_le_bytes(chunk.try_into().unwrap()); } let iv_chunks = iv.chunks_exact(4); for (val, chunk) in state[13..16].iter_mut().zip(iv_chunks) { *val = u32::from_le_bytes(chunk.try_into().unwrap()); } cfg_if! { if #[cfg(chacha20_force_soft)] { let tokens = (); } else if #[cfg(any(target_arch = "x86", target_arch = "x86_64"))] { cfg_if! { if #[cfg(chacha20_force_avx2)] { let tokens = (); } else if #[cfg(chacha20_force_sse2)] { let tokens = (); } else { let tokens = (avx2_cpuid::init(), sse2_cpuid::init()); } } } else { let tokens = (); } } Self { state, tokens, rounds: PhantomData, } } } ``` -------------------------------- ### Try to Get Current Position - Rust Source: https://docs.rs/chacha20/latest/chacha20/type.ChaCha20_search= Attempts to retrieve the current keystream position, returning an error if the position cannot be determined or overflows. This offers robust position retrieval. ```Rust fn try_current_pos(&self) -> Result where SN: SeekNum ``` -------------------------------- ### StreamCipherCoreWrapper Implementations for ChaCha20LegacyCore Source: https://docs.rs/chacha20/latest/chacha20/type.ChaCha20Legacy Provides details on the implementations available for StreamCipherCoreWrapper when used with ChaCha20LegacyCore, including methods for getting and creating core instances, cloning, default initialization, and destruction. ```APIDOC ## Implementations for StreamCipherCoreWrapper ### `get_core` Method #### Description Returns a reference to the core type. #### Method ```rust pub fn get_core(&self) -> &T ``` ### `from_core` Method #### Description Creates a `StreamCipherCoreWrapper` from a given core type. #### Method ```rust pub fn from_core(core: T) -> StreamCipherCoreWrapper ``` ### Trait Implementations #### `Clone` Trait ##### `clone` Method - **Description**: Returns a duplicate of the value. - **Signature**: `fn clone(&self) -> StreamCipherCoreWrapper` ##### `clone_from` Method - **Description**: Performs copy-assignment from `source`. - **Signature**: `fn clone_from(&mut self, source: &Self)` #### `Default` Trait ##### `default` Method - **Description**: Returns the "default value" for a type. - **Signature**: `fn default() -> StreamCipherCoreWrapper` #### `Drop` Trait ##### `drop` Method - **Description**: Executes the destructor for this type. - **Signature**: `fn drop(&mut self)` - **Availability**: Only available with the `zeroize` crate feature. ``` -------------------------------- ### Key Initialization for StreamCipherCoreWrapper - Rust Source: https://docs.rs/chacha20/latest/chacha20/type.XChaCha20_search= Demonstrates how to initialize a StreamCipherCoreWrapper with a key. It supports initialization from a fixed-size GenericArray key or a variable-size byte slice, returning a Result to handle potential errors like invalid key lengths. ```rust impl KeyInit for StreamCipherCoreWrapper where T: KeyInit + BlockSizeUser, ::BlockSize: IsLess, B0>, B0>, B0>, B0>, B0>, B0>, B0>, B0>>, <::BlockSize as IsLess, B0>, B0>, B0>, B0>, B0>, B0>, B0>, B0>>>::Output: NonZero, { fn new( key: &GenericArray as KeySizeUser>::KeySize>, ) -> StreamCipherCoreWrapper { // ... implementation } fn new_from_slice(key: &[u8]) -> Result { // ... implementation } } ``` -------------------------------- ### KeyInit Implementation for StreamCipherCoreWrapper in Rust Source: https://docs.rs/chacha20/latest/chacha20/type.ChaCha8_search=u32+-%3E+bool Implements the KeyInit trait for StreamCipherCoreWrapper, allowing initialization with a key. This includes methods for creating a new cipher from a fixed-size key or a key slice, requiring T to implement KeyInit and BlockSizeUser. ```rust impl KeyInit for StreamCipherCoreWrapper where T: KeyInit + BlockSizeUser, ::BlockSize: IsLess, B0>, B0>, B0>, B0>, B0>, B0>, B0>, B0>>, <::BlockSize as IsLess, B0>, B0>, B0>, B0>, B0>, B0>, B0>, B0>>>::Output: NonZero ``` -------------------------------- ### Seek Keystream Position with StreamCipherCoreWrapper Source: https://docs.rs/chacha20/latest/chacha20/type.ChaCha20 Provides functionality to get and set the current position within the keystream. This allows for resuming encryption/decryption or accessing specific parts of the stream. ```Rust impl StreamCipherSeek for StreamCipherCoreWrapper where T: StreamCipherSeekCore, ::BlockSize: IsLess, B0>, B0>, B0>, B0>, B0>, B0>, B0>, B0>>, <::BlockSize as IsLess, B0>, B0>, B0>, B0>, B0>, B0>, B0>, B0>>>::Output: NonZero, { fn try_current_pos(&self) -> Result where SN: SeekNum, { ::try_current_pos(self) } fn try_seek(&mut self, new_pos: SN) -> Result<(), StreamCipherError> where SN: SeekNum, { ::try_seek(self, new_pos) } fn current_pos(&self) -> SN where SN: SeekNum, { ::current_pos(self) } fn seek(&mut self, pos: SN) where SN: SeekNum, { ::seek(self, pos) } } ``` -------------------------------- ### Initialize ChaCha20 with Key and Nonce in Rust Source: https://docs.rs/chacha20/latest/chacha20/type.ChaCha20 Shows how to initialize a `StreamCipherCoreWrapper` (representing ChaCha20) with both a fixed-size key and a fixed-size nonce (initialization vector). This is part of the `KeyIvInit` trait. ```rust pub fn new( key: &GenericArray as KeySizeUser>::KeySize>, iv: &GenericArray as IvSizeUser>::IvSize>, ) -> StreamCipherCoreWrapper ``` -------------------------------- ### Get Key Size for StreamCipherCoreWrapper Source: https://docs.rs/chacha20/latest/chacha20/type.XChaCha12_search=std%3A%3Avec Retrieves the key size in bytes for a StreamCipherCoreWrapper. This implementation assumes the underlying type T meets specific trait bounds related to block and key sizes. ```rust impl KeySizeUser for StreamCipherCoreWrapper where T: KeySizeUser + BlockSizeUser, ::BlockSize: IsLess, B0>, B0>, B0>, B0>, B0>, B0>, B0>, B0>>, <::BlockSize as IsLess, B0>, B0>, B0>, B0>, B0>, B0>, B0>, B0>>>::Output: NonZero { type KeySize = ::KeySize; fn key_size() -> usize { ::key_size() } } ``` -------------------------------- ### ChaCha20 Stream Cipher Seek Functionality (Rust) Source: https://docs.rs/chacha20/latest/src/chacha20/lib.rs_search= Provides the core stream cipher seek functionality for the ChaChaCore. It allows getting and setting the current block position within the cipher stream. ```Rust impl StreamCipherSeekCore for ChaChaCore { type Counter = u32; #[inline(always)] fn get_block_pos(&self) -> u32 { self.state[12] } #[inline(always)] fn set_block_pos(&mut self, pos: u32) { self.state[12] = pos; } } ``` -------------------------------- ### Key Initialization for StreamCipherCoreWrapper in Rust Source: https://docs.rs/chacha20/latest/chacha20/type.ChaCha20Legacy_search=Option%3CT%3E%2C+%28T+-%3E+U%29+-%3E+Option%3CU%3E Demonstrates how to initialize a StreamCipherCoreWrapper with a key. This function requires a fixed-size key and returns a new instance of the wrapper. The key size is determined by the associated type `KeySizeUser`. ```rust pub fn new( key: &GenericArray as KeySizeUser>::KeySize>, ) -> StreamCipherCoreWrapper ``` -------------------------------- ### Get IV Size in Rust Source: https://docs.rs/chacha20/latest/chacha20/type.XChaCha20_search=u32+-%3E+bool This function, part of the IvSizeUser trait implementation for StreamCipherCoreWrapper, returns the size of the Initialization Vector (IV) in bytes. This is essential for correctly using the cipher with an IV. ```Rust fn iv_size() -> usize ``` -------------------------------- ### Implement Key Initialization for StreamCipherCoreWrapper in Rust Source: https://docs.rs/chacha20/latest/chacha20/type.XChaCha20_search=Option%3CT%3E%2C+%28T+-%3E+U%29+-%3E+Option%3CU%3E This Rust code demonstrates the implementation of key initialization for the StreamCipherCoreWrapper generic type T. It provides methods to create a new instance using a fixed-size key or a slice of bytes, returning a Result to handle potential errors like invalid key lengths. ```rust impl KeyInit for StreamCipherCoreWrapper where T: KeyInit + BlockSizeUser, ::BlockSize: IsLess, B0>, B0>, B0>, B0>, B0>, B0>, B0>, B0>>, <::BlockSize as IsLess, B0>, B0>, B0>, B0>, B0>, B0>, B0>, B0>>>::Output: NonZero, { fn new( key: &GenericArray as KeySizeUser>::KeySize>, ) -> StreamCipherCoreWrapper { // ... implementation details ... } fn new_from_slice(key: &[u8]) -> Result { // ... implementation details ... } } ``` -------------------------------- ### Equality Implementation Source: https://docs.rs/chacha20/latest/chacha20/type.Nonce Documentation for equality comparison of GenericArray instances. ```APIDOC ### impl PartialEq for GenericArray ### Description Enables equality comparison for `GenericArray` instances if the element type `T` supports equality comparison. ### Methods #### `fn eq(&self, other: &GenericArray) -> bool` Tests if `self` is equal to `other`. - **other** (&GenericArray) - The other array to compare against. - Returns `true` if the arrays are equal, `false` otherwise. ``` ```APIDOC #### `fn ne(&self, other: &Rhs) -> bool` Tests if `self` is not equal to `other`. - **other** (&Rhs) - The other value to compare against. - Returns `true` if the arrays are not equal, `false` otherwise. ```