### Rust Search Examples Source: https://docs.rs/argon2/0.5.3/src/argon2/lib.rs.html?search=u32+-%3E+bool Provides examples of common search queries used to find information within Rust documentation. These demonstrate how to search for specific types, traits, and function signatures. ```text std::vec ``` ```text u32 -> bool ``` ```text Option, (T -> U) -> Option ``` -------------------------------- ### Password Hashing Example Source: https://docs.rs/argon2/0.5.3/argon2/index.html This example demonstrates how to hash a password to a PHC string using the Argon2 crate. It utilizes the default Argon2id parameters and shows how to generate a salt and verify the password against the generated hash. ```APIDOC ## Password Hashing This API hashes a password to a “PHC string” suitable for the purposes of password-based authentication. Do not use this API to derive cryptographic keys: see the “key derivation” usage example below. ```rust use argon2::{ password_hash::{ rand_core::OsRng, PasswordHash, PasswordHasher, PasswordVerifier, SaltString }, Argon2 }; let password = b"hunter42"; // Bad password; don't actually use! let salt = SaltString::generate(&mut OsRng); // Argon2 with default params (Argon2id v19) let argon2 = Argon2::default(); // Hash password to PHC string ($argon2id$v=19$...) let password_hash = argon2.hash_password(password, &salt)?.to_string(); // Verify password against PHC string. // // NOTE: hash params from `parsed_hash` are used instead of what is configured in the // `Argon2` instance. let parsed_hash = PasswordHash::new(&password_hash)?; assert!(Argon2::default().verify_password(password, &parsed_hash).is_ok()); ``` ``` -------------------------------- ### Key Derivation Example Source: https://docs.rs/argon2/0.5.3/argon2/index.html This example shows how to use the Argon2 crate to derive cryptographic keys from a password, which is useful for password-based encryption. It demonstrates hashing a password and salt into a specified output key material size. ```APIDOC ## Key Derivation This API is useful for transforming a password into cryptographic keys for e.g. password-based encryption. ```rust use argon2::Argon2; let password = b"hunter42"; // Bad password; don't actually use! let salt = b"example salt"; // Salt should be unique per password let mut output_key_material = [0u8; 32]; // Can be any desired size Argon2::default().hash_password_into(password, salt, &mut output_key_material)?; ``` ``` -------------------------------- ### Key Derivation Source: https://docs.rs/argon2/0.5.3/src/argon2/lib.rs.html?search=std%3A%3Avec This example shows how to use Argon2 to derive cryptographic keys from a password and salt. ```APIDOC ## Key Derivation This API is useful for transforming a password into cryptographic keys for e.g. password-based encryption. ``` # fn main() -> Result<(), Box> { use argon2::Argon2; let password = b"hunter42"; // Bad password; don't actually use! let salt = b"example salt"; // Salt should be unique per password let mut output_key_material = [0u8; 32]; // Can be any desired size Argon2::default().hash_password_into(password, salt, &mut output_key_material)?; # Ok(()) # } ``` ``` -------------------------------- ### Password Hashing Source: https://docs.rs/argon2/0.5.3/src/argon2/lib.rs.html?search=std%3A%3Avec This example demonstrates how to hash a password to a PHC string using Argon2 with default parameters and then verify it. ```APIDOC ## Password Hashing This API hashes a password to a "PHC string" suitable for the purposes of password-based authentication. Do not use this API to derive cryptographic keys: see the "key derivation" usage example below. ``` # fn main() -> Result<(), Box> { use argon2::{ password_hash::{ rand_core::OsRng, PasswordHash, PasswordHasher, PasswordVerifier, SaltString }, Argon2 }; let password = b"hunter42"; // Bad password; don't actually use! let salt = SaltString::generate(&mut OsRng); // Argon2 with default params (Argon2id v19) let argon2 = Argon2::default(); // Hash password to PHC string ($argon2id$v=19$...) let password_hash = argon2.hash_password(password, &salt)?.to_string(); // Verify password against PHC string. // // NOTE: hash params from `parsed_hash` are used instead of what is configured in the // `Argon2` instance. let parsed_hash = PasswordHash::new(&password_hash)?; assert!(Argon2::default().verify_password(password, &parsed_hash).is_ok()); # Ok(()) # } ``` ``` -------------------------------- ### Create New ParamsBuilder Source: https://docs.rs/argon2/0.5.3/argon2/struct.ParamsBuilder.html Initializes a new ParamsBuilder with default settings. Use this to start configuring custom parameters. ```rust pub const fn new() -> Self ``` -------------------------------- ### Initialize ParamsBuilder Source: https://docs.rs/argon2/0.5.3/argon2/struct.ParamsBuilder.html?search=Option%3CT%3E%2C+%28T+-%3E+U%29+-%3E+Option%3CU%3E Creates a new ParamsBuilder with default parameters. This is the recommended starting point for configuring Argon2 parameters. ```rust pub struct ParamsBuilder { /* private fields */ } ``` ```rust pub const DEFAULT: ParamsBuilder ``` ```rust pub const fn new() -> Self ``` -------------------------------- ### Initialize First Two Blocks in Each Lane (Rust) Source: https://docs.rs/argon2/0.5.3/src/argon2/lib.rs.html?search=std%3A%3Avec Initializes the first two blocks in each lane using a hash derived from initial parameters. This is a setup step before the main hashing passes. ```rust for (l, lane) in memory_blocks.chunks_exact_mut(lane_length).enumerate() { for (i, block) in lane[..2].iter_mut().enumerate() { let i = i as u32; let l = l as u32; // Make the first and second block in each lane as G(H0||0||i) or // G(H0||1||i) let inputs = &[ initial_hash.as_ref(), &i.to_le_bytes()[..], &l.to_le_bytes()[..], ]; let mut hash = [0u8; Block::SIZE]; blake2b_long(inputs, &mut hash)?; block.load(&hash); } } ``` -------------------------------- ### Get Default Parameters Source: https://docs.rs/argon2/0.5.3/argon2/struct.Argon2.html?search=Option%3CT%3E%2C+%28T+-%3E+U%29+-%3E+Option%3CU%3E Retrieves the default configured `Params` for the Argon2 context. ```rust pub const fn params(&self) -> &Params ``` -------------------------------- ### ParamsBuilder::new Source: https://docs.rs/argon2/0.5.3/src/argon2/params.rs.html?search= Initializes a new `ParamsBuilder` with default Argon2 parameters. Use this as a starting point before configuring specific costs and identifiers. ```rust pub const fn new() -> Self { Self::DEFAULT } ``` -------------------------------- ### Argon2i/Argon2id Data Independent Addressing Setup (Rust) Source: https://docs.rs/argon2/0.5.3/src/argon2/lib.rs.html?search=std%3A%3Avec Sets up input block for data-independent addressing in Argon2i or early passes of Argon2id. This is used when the algorithm needs to generate addresses deterministically. ```rust if data_independent_addressing { input_block.as_mut()[..6].copy_from_slice(&[ pass as u64, lane as u64, slice as u64, memory_blocks.len() as u64, iterations as u64, self.algorithm as u64, ]); } ``` -------------------------------- ### Password Hashing with Argon2 Source: https://docs.rs/argon2/0.5.3/src/argon2/lib.rs.html?search=u32+-%3E+bool Demonstrates how to hash a password to a PHC string using Argon2 with default parameters. This is suitable for password-based authentication. The example also shows how to verify the password against the generated hash. ```rust use argon2::{ password_hash::{ rand_core::OsRng, PasswordHash, PasswordHasher, PasswordVerifier, SaltString }, Argon2 }; let password = b"hunter42"; // Bad password; don't actually use! let salt = SaltString::generate(&mut OsRng); // Argon2 with default params (Argon2id v19) let argon2 = Argon2::default(); // Hash password to PHC string ($argon2id$v=19$...) let password_hash = argon2.hash_password(password, &salt)?.to_string(); // Verify password against PHC string. // // NOTE: hash params from `parsed_hash` are used instead of what is configured in the // `Argon2` instance. let parsed_hash = PasswordHash::new(&password_hash)?; assert!(Argon2::default().verify_password(password, &parsed_hash).is_ok()); ``` -------------------------------- ### ParamsBuilder::new Source: https://docs.rs/argon2/0.5.3/argon2/struct.ParamsBuilder.html Creates a new ParamsBuilder with default Argon2 parameters. This is the recommended starting point for configuring hashing parameters. ```APIDOC ## ParamsBuilder::new ### Description Creates a new builder with the default parameters. ### Signature ```rust pub const fn new() -> Self ``` ``` -------------------------------- ### Algorithm Methods Source: https://docs.rs/argon2/0.5.3/src/argon2/algorithm.rs.html?search=Option%3CT%3E%2C+%28T+-%3E+U%29+-%3E+Option%3CU%3E Provides methods for creating an `Algorithm` from a string, getting its string representation, and retrieving its corresponding `Ident` for use with the `password-hash` crate. ```APIDOC impl Algorithm { /// Parse an [`Algorithm`] from the provided string. pub fn new(id: impl AsRef) -> Result; /// Get the identifier string for this PBKDF2 [`Algorithm`]. pub const fn as_str(&self) -> &'static str; /// Get the [`Ident`] that corresponds to this Argon2 [`Algorithm`]. #[cfg(feature = "password-hash")] #[cfg_attr(docsrs, doc(cfg(feature = "password-hash")))] pub const fn ident(&self) -> Ident<'static>; /// Serialize primitive type as little endian bytes pub(crate) const fn to_le_bytes(self) -> [u8; 4]; } ``` -------------------------------- ### Handling File Metadata with `and_then` Source: https://docs.rs/argon2/0.5.3/argon2/type.Result.html?search= Demonstrates chaining fallible operations like getting file metadata and its modification time. This is useful for sequential operations where any step might fail. ```rust use std::{io::ErrorKind, path::Path}; // Note: on Windows "/" maps to "C:\\" let root_modified_time = Path::new("/").metadata().and_then(|md| md.modified()); assert!(root_modified_time.is_ok()); let should_fail = Path::new("/bad/path").metadata().and_then(|md| md.modified()); assert!(should_fail.is_err()); assert_eq!(should_fail.unwrap_err().kind(), ErrorKind::NotFound); ``` -------------------------------- ### Block Constants and Methods Source: https://docs.rs/argon2/0.5.3/argon2/struct.Block.html?search=u32+-%3E+bool Details on the Block's size and how to create a new instance. ```APIDOC ### impl Block #### pub const SIZE: usize = 1_024usize Memory block size in bytes #### pub const fn new() -> Self Returns a Block initialized with zeros. ``` -------------------------------- ### lanes() Source: https://docs.rs/argon2/0.5.3/src/argon2/params.rs.html?search=std%3A%3Avec Gets the number of lanes, derived from the p_cost. ```APIDOC ## lanes() ### Description Gets the number of lanes, derived from the p_cost. ### Signature `pub(crate) const fn lanes(&self) -> usize` ``` -------------------------------- ### Basic Result Usage Source: https://docs.rs/argon2/0.5.3/argon2/type.Result.html?search=Option%3CT%3E%2C+%28T+-%3E+U%29+-%3E+Option%3CU%3E Demonstrates the basic usage of `Ok` variant of `Result` with `unwrap`. ```rust let x: Result = Ok(2); assert_eq!(x.unwrap(), 2); ``` -------------------------------- ### PasswordHash::encoding Source: https://docs.rs/argon2/0.5.3/argon2/struct.PasswordHash.html?search=std%3A%3Avec Gets the Encoding that this PasswordHash is serialized with. ```APIDOC ## PasswordHash::encoding ### Description Get the `Encoding` that this `PasswordHash` is serialized with. ### Signature `pub fn encoding(&self) -> Encoding` ### Returns * `Encoding` - The encoding used for serialization. ``` -------------------------------- ### PasswordHash::encoding Source: https://docs.rs/argon2/0.5.3/argon2/struct.PasswordHash.html Gets the Encoding that this PasswordHash is serialized with. ```APIDOC ## `encoding` - Method ### Description Get the `Encoding` that this `PasswordHash` is serialized with. ### Signature ```rust pub fn encoding(&self) -> Encoding ``` ``` -------------------------------- ### AssociatedData::len Source: https://docs.rs/argon2/0.5.3/argon2/struct.AssociatedData.html?search=std%3A%3Avec Gets the length in bytes of the AssociatedData. ```APIDOC ## AssociatedData::len ### Description Get the length in bytes. ### Method Signature `pub const fn len(&self) -> usize;` ``` -------------------------------- ### KeyId Creation Methods Source: https://docs.rs/argon2/0.5.3/argon2/struct.KeyId.html Methods for creating a KeyId instance. `new` creates from a byte slice, and `from_b64` decodes from a Base64 string. ```rust pub fn new(slice: &[u8]) -> Result ``` ```rust pub fn from_b64(s: &str) -> Result ``` -------------------------------- ### AssociatedData::len Source: https://docs.rs/argon2/0.5.3/argon2/struct.AssociatedData.html?search=Option%3CT%3E%2C+%28T+-%3E+U%29+-%3E+Option%3CU%3E Gets the length in bytes of the AssociatedData. ```APIDOC ## AssociatedData::len ### Description Get the length in bytes. ### Method `pub const fn len(&self) -> usize` ### Returns `usize`: The length of the AssociatedData in bytes. ``` -------------------------------- ### impl Any for T Source: https://docs.rs/argon2/0.5.3/argon2/enum.Algorithm.html?search=Option%3CT%3E%2C+%28T+-%3E+U%29+-%3E+Option%3CU%3E Provides the `type_id` method to get the `TypeId` of an object. ```APIDOC ## fn type_id(&self) -> TypeId ### Description Gets the `TypeId` of `self`. ### Parameters None ### Returns - `TypeId`: The unique identifier for the type of `self`. ``` -------------------------------- ### Algorithm::as_str Source: https://docs.rs/argon2/0.5.3/argon2/enum.Algorithm.html?search= Gets the identifier string for this Argon2 `Algorithm`. ```APIDOC #### pub const fn as_str(&self) -> &'static str Get the identifier string for this PBKDF2 `Algorithm`. ``` -------------------------------- ### output_len Source: https://docs.rs/argon2/0.5.3/src/argon2/params.rs.html?search=Option%3CT%3E%2C+%28T+-%3E+U%29+-%3E+Option%3CU%3E Gets the length of the output in bytes. Returns an Option. ```APIDOC ## output_len ### Description Gets the desired length of the output hash in bytes. ### Return Value - `Option`: The length of the output in bytes, or `None` if not specified. ### Method Signature `pub const fn output_len(&self) -> Option` ``` -------------------------------- ### Argon2::new Source: https://docs.rs/argon2/0.5.3/argon2/struct.Argon2.html?search=std%3A%3Avec Creates a new Argon2 context with the specified algorithm, version, and parameters. ```APIDOC ## Argon2::new ### Description Create a new Argon2 context. ### Signature `pub fn new(algorithm: Algorithm, version: Version, params: Params) -> Self` ``` -------------------------------- ### Argon2::new Source: https://docs.rs/argon2/0.5.3/argon2/struct.Argon2.html Creates a new Argon2 context with the specified algorithm, version, and parameters. ```APIDOC ## Argon2::new ### Description Create a new Argon2 context. ### Signature ```rust pub fn new(algorithm: Algorithm, version: Version, params: Params) -> Self ``` ``` -------------------------------- ### output_len() Source: https://docs.rs/argon2/0.5.3/src/argon2/params.rs.html?search=std%3A%3Avec Gets the length of the output in bytes. Returns an Option. ```APIDOC ## output_len() ### Description Gets the length of the output in bytes. Returns an Option. ### Signature `pub const fn output_len(&self) -> Option` ``` -------------------------------- ### ParamBuf::len Source: https://docs.rs/argon2/0.5.3/src/argon2/params.rs.html?search=Option%3CT%3E%2C+%28T+-%3E+U%29+-%3E+Option%3CU%3E Gets the current length in bytes of the data stored in the ParamBuf. ```APIDOC ## ParamBuf::len ### Description Returns the number of bytes currently stored in the ParamBuf. ### Return Value - `usize`: The length of the data in bytes. ### Method Signature `pub const fn len(&self) -> usize` ``` -------------------------------- ### Create New Argon2 Context Source: https://docs.rs/argon2/0.5.3/argon2/struct.Argon2.html?search=Option%3CT%3E%2C+%28T+-%3E+U%29+-%3E+Option%3CU%3E Initializes a new Argon2 context with a specified algorithm, version, and parameters. This is the primary way to set up the hashing context. ```rust pub fn new(algorithm: Algorithm, version: Version, params: Params) -> Self ``` -------------------------------- ### Initialize ParamsBuilder Source: https://docs.rs/argon2/0.5.3/argon2/struct.ParamsBuilder.html?search=u32+-%3E+bool Create a new builder with default parameters or use the predefined default instance. ```rust pub const DEFAULT: ParamsBuilder ``` ```rust pub const fn new() -> Self ``` -------------------------------- ### into_ok Source: https://docs.rs/argon2/0.5.3/argon2/type.Result.html?search=u32+-%3E+bool Returns the contained Ok value, never panics. This is a nightly-only experimental API. ```APIDOC ## into_ok ### Description Returns the contained `Ok` value, but never panics. This method is known to never panic on the result types it is implemented for, making it a maintainability safeguard. ### Method `into_ok()` ### Parameters None ### Response - `T`: The contained `Ok` value. ### Request Example ```rust fn only_good_news() -> Result { Ok("this is fine".into()) } let s: String = only_good_news().into_ok(); println!("{s}"); ``` ### Response Example ```rust // Returns the Ok value. Will not compile if the Err type can actually occur. ``` ``` -------------------------------- ### Block Initialization and Loading Source: https://docs.rs/argon2/0.5.3/src/argon2/block.rs.html?search=std%3A%3Avec Provides methods to create a new zero-initialized `Block` and load data from a byte slice. ```rust pub const fn new() -> Self { Self([0u64; Self::SIZE / 8]) } ``` ```rust pub(crate) fn load(&mut self, input: &[u8; Block::SIZE]) { for (i, chunk) in input.chunks(8).enumerate() { self.0[i] = u64::from_le_bytes(chunk.try_into().expect("should be 8 bytes")); } } ``` -------------------------------- ### lane_length() Source: https://docs.rs/argon2/0.5.3/src/argon2/params.rs.html?search=std%3A%3Avec Gets the number of blocks in a lane, calculated based on segment length and sync points. ```APIDOC ## lane_length() ### Description Gets the number of blocks in a lane, calculated based on segment length and sync points. ### Signature `pub(crate) const fn lane_length(&self) -> usize` ``` -------------------------------- ### KeyId Conversions Source: https://docs.rs/argon2/0.5.3/argon2/struct.KeyId.html Demonstrates conversions to and from KeyId using standard Rust traits. ```APIDOC ## KeyId Conversions This section covers the conversion capabilities of the `KeyId` struct through standard Rust traits. ### `impl Into for T where U: From` This implementation allows converting a type `T` into a type `U` if `U` implements the `From` trait. #### `fn into(self) -> U` Calls `U::from(self)`. The conversion logic is determined by the specific `From for U` implementation. ### `impl Same for T` This is a placeholder for a trait named `Same` which is implemented for type `T`. #### `type Output = T` The associated type `Output` should always be `Self`. ### `impl ToOwned for T where T: Clone` This implementation allows creating an owned version of a type `T` if `T` implements the `Clone` trait. #### `type Owned = T` The `Owned` associated type is the type that represents ownership, which is `T` in this case. #### `fn to_owned(&self) -> T` Creates owned data from borrowed data, typically by cloning. #### `fn clone_into(&self, target: &mut T)` Uses borrowed data to replace owned data, usually by cloning. ### `impl TryFrom for T where U: Into` This implementation allows attempting to convert a type `U` into a type `T` if `U` implements the `Into` trait. This conversion can fail. #### `type Error = Infallible` The `Error` associated type is `Infallible`, indicating that this specific `TryFrom` implementation does not produce errors. #### `fn try_from(value: U) -> Result>::Error>` Performs the conversion. Returns a `Result` which will always be `Ok` in this case due to `Infallible` error type. ### `impl TryInto for T where U: TryFrom` This implementation allows attempting to convert a type `T` into a type `U` if `U` implements the `TryFrom` trait. This conversion can fail. #### `type Error = >::Error` The `Error` associated type is derived from the `Error` type of the `TryFrom` implementation for `U`. #### `fn try_into(self) -> Result>::Error>` Performs the conversion. Returns a `Result` which may be `Ok` or `Err` depending on the success of the underlying `TryFrom` conversion. ``` -------------------------------- ### KeyId Length and Emptiness Check Source: https://docs.rs/argon2/0.5.3/argon2/struct.KeyId.html Methods to get the length of the KeyId in bytes and to check if it is empty. ```rust pub const fn len(&self) -> usize ``` ```rust pub const fn is_empty(&self) -> bool ``` -------------------------------- ### Get Length of Argon2 AssociatedData Source: https://docs.rs/argon2/0.5.3/argon2/struct.AssociatedData.html Returns the length in bytes of the AssociatedData. This is a constant time operation. ```rust pub const fn len(&self) -> usize ``` -------------------------------- ### TryFrom and TryInto for ParamsBuilder Source: https://docs.rs/argon2/0.5.3/argon2/struct.ParamsBuilder.html?search=u32+-%3E+bool Implement `TryFrom` and `TryInto` for `ParamsBuilder`, allowing fallible conversions. ```rust type Error = Infallible ``` ```rust fn try_from(value: U) -> Result>::Error> ``` ```rust type Error = >::Error ``` -------------------------------- ### Algorithm::ident Source: https://docs.rs/argon2/0.5.3/argon2/enum.Algorithm.html?search= Gets the `Ident` that corresponds to this Argon2 `Algorithm`. Available on `crate feature`password-hash` only. ```APIDOC #### pub const fn ident(&self) -> Ident<'static> Available on **crate feature`password-hash`** only. Get the `Ident` that corresponds to this Argon2 `Algorithm`. ``` -------------------------------- ### Create Argon2 Context Source: https://docs.rs/argon2/0.5.3/src/argon2/lib.rs.html?search=u32+-%3E+bool Initializes a new Argon2 context with specified algorithm, version, and parameters. The default implementation is used if no specific configuration is provided. ```rust pub fn new(algorithm: Algorithm, version: Version, params: Params) -> Self ``` ```rust impl Default for Argon2<'_> { fn default() -> Self { Self::new(Algorithm::default(), Version::default(), Params::default()) } } ``` -------------------------------- ### Get Memory Cost Source: https://docs.rs/argon2/0.5.3/src/argon2/params.rs.html?search=u32+-%3E+bool Retrieves the memory cost parameter for Argon2 hashing, expressed in 1 KiB blocks. ```rust pub const fn m_cost(&self) -> u32 { self.m_cost } ``` -------------------------------- ### TryInto for Argon2 Version Types Source: https://docs.rs/argon2/0.5.3/argon2/enum.Version.html?search= This snippet shows the implementation of `TryInto` for Argon2 version types, enabling conversion to other types and providing an error type for failed conversions. ```APIDOC ## impl TryInto for T where U: TryFrom { #### type Error = >::Error The type returned in the event of a conversion error. #### fn try_into(self) -> Result>::Error> Performs the conversion. #### fn try_from(value: U) -> Result>::Error> Performs the conversion. } ``` -------------------------------- ### Get Argon2 Algorithm as String Source: https://docs.rs/argon2/0.5.3/src/argon2/algorithm.rs.html?search= Returns the string representation of the Argon2 algorithm. This is useful for serialization or display purposes. ```rust /// Get the identifier string for this PBKDF2 [`Algorithm`]. pub const fn as_str(&self) -> &'static str { match self { Algorithm::Argon2d => "argon2d", Algorithm::Argon2i => "argon2i", Algorithm::Argon2id => "argon2id", } } ``` -------------------------------- ### Block::new Source: https://docs.rs/argon2/0.5.3/argon2/struct.Block.html?search=Option%3CT%3E%2C+%28T+-%3E+U%29+-%3E+Option%3CU%3E Creates and returns a new `Block` instance initialized with zeros. ```APIDOC ### `pub fn new() -> Self` Returns a Block initialized with zeros. ``` -------------------------------- ### CloneToUninit Source: https://docs.rs/argon2/0.5.3/argon2/struct.AssociatedData.html?search=std%3A%3Avec Provides an unsafe method to perform copy-assignment from self to a destination pointer. This is a nightly-only experimental API. ```APIDOC ## unsafe fn clone_to_uninit(&self, dest: *mut u8) ### Description Performs copy-assignment from `self` to `dest`. ### Method `unsafe fn clone_to_uninit` ### Parameters - `dest` (*mut u8) - The destination pointer to copy the data to. ### Notes This is a nightly-only experimental API. ``` -------------------------------- ### Initialize Argon2 ParamsBuilder Source: https://docs.rs/argon2/0.5.3/src/argon2/params.rs.html Creates a new `ParamsBuilder` with default parameters. This builder is used to construct Argon2 `Params` by setting various costs and identifiers. ```rust impl ParamsBuilder { /// Create a new builder with the default parameters. pub const fn new() -> Self { Self::DEFAULT } // ... other methods ... } ``` -------------------------------- ### TryFrom Implementations for PasswordHash and ParamsString Source: https://docs.rs/argon2/0.5.3/src/argon2/params.rs.html?search= Conversions between PasswordHash, Params, and ParamsString. ```APIDOC ## TryFrom<&'a PasswordHash<'a>> for Params ### Description Converts a `PasswordHash` into `Params`. ### Method `try_from(hash: &'a PasswordHash<'a>) -> password_hash::Result` ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example None ### Response #### Success Response (200) - **Params** (Params) - The converted Argon2 parameters. #### Response Example None ## TryFrom for ParamsString ### Description Converts `Params` into `ParamsString`. ### Method `try_from(params: Params) -> password_hash::Result` ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example None ### Response #### Success Response (200) - **ParamsString** (ParamsString) - The string representation of the parameters. #### Response Example None ## TryFrom<&Params> for ParamsString ### Description Converts a reference to `Params` into `ParamsString`. ### Method `try_from(params: &Params) -> password_hash::Result` ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example None ### Response #### Success Response (200) - **ParamsString** (ParamsString) - The string representation of the parameters. #### Response Example None ``` -------------------------------- ### PasswordHash::encoding - Get Encoding Source: https://docs.rs/argon2/0.5.3/argon2/struct.PasswordHash.html?search= Retrieves the encoding scheme used by this PasswordHash instance. This is useful for understanding how the hash is serialized. ```rust pub fn encoding(&self) -> Encoding ``` -------------------------------- ### Get Argon2 Algorithm Ident Source: https://docs.rs/argon2/0.5.3/argon2/enum.Algorithm.html?search= Retrieves the `Ident` corresponding to the Argon2 `Algorithm`. This is available when the `password-hash` crate feature is enabled. ```rust pub const fn ident(&self) -> Ident<'static> ``` -------------------------------- ### Error::cause Implementation (Deprecated) Source: https://docs.rs/argon2/0.5.3/argon2/enum.Error.html?search=Option%3CT%3E%2C+%28T+-%3E+U%29+-%3E+Option%3CU%3E A deprecated method for getting the underlying cause of an error. `Error::source` is the preferred alternative. ```rust fn cause(&self) -> Option<&dyn Error> ``` -------------------------------- ### Compare Argon2 Algorithms Source: https://docs.rs/argon2/0.5.3/argon2/enum.Algorithm.html?search= Provides comparison methods for Argon2 `Algorithm` variants, enabling ordering and equality checks. These are part of the `PartialOrd` and `Ord` traits. ```rust fn cmp(&self, other: &Algorithm) -> Ordering ``` ```rust fn partial_cmp(&self, other: &Algorithm) -> Option ``` ```rust fn eq(&self, other: &Algorithm) -> bool ``` ```rust fn ne(&self, other: &Rhs) -> bool ``` ```rust fn lt(&self, other: &Rhs) -> bool ``` ```rust fn le(&self, other: &Rhs) -> bool ``` ```rust fn gt(&self, other: &Rhs) -> bool ``` ```rust fn ge(&self, other: &Rhs) -> bool ``` -------------------------------- ### Clone ParamsBuilder Source: https://docs.rs/argon2/0.5.3/argon2/struct.ParamsBuilder.html?search=Option%3CT%3E%2C+%28T+-%3E+U%29+-%3E+Option%3CU%3E Returns a duplicate of the `ParamsBuilder` value. This allows for creating multiple configurations based on a common starting point. ```rust fn clone(&self) -> ParamsBuilder ``` -------------------------------- ### Error::provide Implementation (Nightly) Source: https://docs.rs/argon2/0.5.3/argon2/enum.Error.html?search=Option%3CT%3E%2C+%28T+-%3E+U%29+-%3E+Option%3CU%3E An experimental, nightly-only API for providing type-based access to error context, intended for error reporting. ```rust fn provide<'a>(&'a self, request: &mut Request<'a>) ``` -------------------------------- ### fn report(self) -> ExitCode Source: https://docs.rs/argon2/0.5.3/argon2/type.Result.html?search=Option%3CT%3E%2C+%28T+-%3E+U%29+-%3E+Option%3CU%3E Is called to get the representation of the value as status code. This status code is returned to the operating system. ```APIDOC ## fn report(self) -> ExitCode ### Description Is called to get the representation of the value as status code. This status code is returned to the operating system. ### Parameters None ### Request Example None ### Response #### Success Response (200) - **status_code** (ExitCode) - The status code representing the Result. ### Response Example None ``` -------------------------------- ### Argon2 Initialization from Params Source: https://docs.rs/argon2/0.5.3/src/argon2/lib.rs.html?search=u32+-%3E+bool Provides convenient ways to create an Argon2 hasher instance directly from `Params` using `From` trait implementations. ```rust impl<'key> From for Argon2<'key> { fn from(params: Params) -> Self { Self::new(Algorithm::default(), Version::default(), params) } } ``` ```rust impl<'key> From<&Params> for Argon2<'key> { fn from(params: &Params) -> Self { Self::from(params.clone()) } } ``` -------------------------------- ### p_cost Source: https://docs.rs/argon2/0.5.3/src/argon2/params.rs.html?search=Option%3CT%3E%2C+%28T+-%3E+U%29+-%3E+Option%3CU%3E Gets the degree of parallelism. This value must be between 1 and (2^24)-1 and is provided as a decimal integer (1 to 3 digits). ```APIDOC ## p_cost ### Description Gets the degree of parallelism for the Argon2 algorithm. ### Constraints - Value must be between 1 and (2^24)-1. - Provided as a decimal integer (1 to 3 digits). ### Method Signature `pub const fn p_cost(&self) -> u32` ``` -------------------------------- ### impl CloneToUninit for T Source: https://docs.rs/argon2/0.5.3/argon2/enum.Algorithm.html?search=Option%3CT%3E%2C+%28T+-%3E+U%29+-%3E+Option%3CU%3E Provides an unsafe method for cloning data to an uninitialized memory location. This is a nightly-only experimental API. ```APIDOC ## unsafe fn clone_to_uninit(&self, dest: *mut u8) ### Description Performs copy-assignment from `self` to `dest`. ### Parameters - `dest` (*mut u8): A pointer to the destination memory location. ### Safety This function is unsafe because it operates on raw pointers and assumes `dest` is valid and sufficiently large to hold the cloned data. ``` -------------------------------- ### TryFrom for Version Implementation Source: https://docs.rs/argon2/0.5.3/argon2/enum.Version.html?search=Option%3CT%3E%2C+%28T+-%3E+U%29+-%3E+Option%3CU%3E This implementation allows attempting to convert a `u32` value into a `Version` enum value, returning a `Result`. ```APIDOC ### impl TryFrom for Version #### type Error = Error The type returned in the event of a conversion error. #### fn try_from(version_id: u32) -> Result Performs the conversion. ``` -------------------------------- ### t_cost Source: https://docs.rs/argon2/0.5.3/src/argon2/params.rs.html?search=Option%3CT%3E%2C+%28T+-%3E+U%29+-%3E+Option%3CU%3E Gets the number of iterations. This value must be between 1 and (2^32)-1 and is provided as a decimal integer (1 to 10 digits). ```APIDOC ## t_cost ### Description Gets the number of iterations for the Argon2 algorithm. ### Constraints - Value must be between 1 and (2^32)-1. - Provided as a decimal integer (1 to 10 digits). ### Method Signature `pub const fn t_cost(&self) -> u32` ``` -------------------------------- ### Block Implementations Source: https://docs.rs/argon2/0.5.3/src/argon2/block.rs.html Provides implementations for `Default`, `AsRef`, `AsMut`, `BitXor`, `BitXorAssign`, and `Zeroize` (when the `zeroize` feature is enabled) for the `Block` struct. ```APIDOC ## Block Implementations ### `Default` Trait - `default()`: `fn default() -> Self` - Implements the `Default` trait, providing a default `Block` initialized with zeros. ### `AsRef<[u64]>` Trait - `as_ref()`: `fn as_ref(&self) -> &[u64]` - Returns a slice view of the `u64` words in the block. ### `AsMut<[u64]>` Trait - `as_mut()`: `fn as_mut(&mut self) -> &mut [u64]` - Returns a mutable slice view of the `u64` words in the block. ### `BitXor` and `BitXorAssign` Traits - `bitxor(self, rhs: &Block)`: `fn bitxor(mut self, rhs: &Block) -> Self::Output` - Performs a bitwise XOR operation between two blocks. - `bitxor_assign(&mut self, rhs: &Block)`: `fn bitxor_assign(&mut self, rhs: &Block)` - Performs a bitwise XOR operation in place. ### `Zeroize` Trait (with `zeroize` feature) - `zeroize()`: `fn zeroize(&mut self)` - Clears the block's memory by overwriting it with zeros. ``` -------------------------------- ### Error::description Implementation (Deprecated) Source: https://docs.rs/argon2/0.5.3/argon2/enum.Error.html?search=Option%3CT%3E%2C+%28T+-%3E+U%29+-%3E+Option%3CU%3E A deprecated method for getting a string description of the error. Prefer using the `Display` implementation or `to_string()`. ```rust fn description(&self) -> &str ``` -------------------------------- ### Create New Argon2 Context Source: https://docs.rs/argon2/0.5.3/src/argon2/lib.rs.html?search=Option%3CT%3E%2C+%28T+-%3E+U%29+-%3E+Option%3CU%3E Initializes a new Argon2 context with specified algorithm, version, and parameters. The secret key is optional. ```rust pub fn new(algorithm: Algorithm, version: Version, params: Params) -> Self { Self { algorithm, version, params, secret: None, #[cfg(any(target_arch = "x86", target_arch = "x86_64"))] cpu_feat_avx2: avx2_cpuid::init(), } } ``` -------------------------------- ### Key Derivation with Argon2 Source: https://docs.rs/argon2/0.5.3/argon2/index.html?search= This API is suitable for deriving cryptographic keys from a password, for example, in password-based encryption. The salt should be unique per password. ```rust use argon2::Argon2; let password = b"hunter42"; // Bad password; don't actually use! let salt = b"example salt"; // Salt should be unique per password let mut output_key_material = [0u8; 32]; // Can be any desired size Argon2::default().hash_password_into(password, salt, &mut output_key_material)?; ``` -------------------------------- ### TryFrom for Params Source: https://docs.rs/argon2/0.5.3/argon2/struct.Params.html?search= Converts Argon2 ParamsBuilder into Argon2 Params. ```APIDOC ## impl TryFrom for Params ### Description Converts a `ParamsBuilder` into `Params`. ### Type Alias #### type Error = Error ### Method #### fn try_from(builder: ParamsBuilder) -> Result ``` -------------------------------- ### Compute Initial Hash for Argon2 Source: https://docs.rs/argon2/0.5.3/src/argon2/lib.rs.html?search=std%3A%3Avec Calculates the initial hash for the Argon2 algorithm using Blake2b512. It incorporates parameters like costs, output length, and version. ```rust fn initial_hash(&self, pwd: &[u8], salt: &[u8], out: &[u8]) -> digest::Output { let mut digest = Blake2b512::new(); digest.update(self.params.p_cost().to_le_bytes()); digest.update((out.len() as u32).to_le_bytes()); digest.update(self.params.m_cost().to_le_bytes()); digest.update(self.params.t_cost().to_le_bytes()); digest.update(self.version.to_le_bytes()); } ``` -------------------------------- ### KeyId Byte Slice Access and Length Source: https://docs.rs/argon2/0.5.3/argon2/struct.KeyId.html?search=Option%3CT%3E%2C+%28T+-%3E+U%29+-%3E+Option%3CU%3E Provides methods to borrow the inner value as a byte slice and to get the length of the KeyId in bytes. ```rust pub fn as_bytes(&self) -> &[u8] ⓘ ``` ```rust pub const fn len(&self) -> usize ``` -------------------------------- ### Providing a Default Value with `unwrap_or` Source: https://docs.rs/argon2/0.5.3/argon2/type.Result.html?search=Option%3CT%3E%2C+%28T+-%3E+U%29+-%3E+Option%3CU%3E Use `unwrap_or` to get the Ok value or a default value if the Result is an Err. The default value is always evaluated. ```rust let default = 2; let x: Result = Ok(9); assert_eq!(x.unwrap_or(default), 9); let x: Result = Err("error"); assert_eq!(x.unwrap_or(default), default); ``` -------------------------------- ### pub fn ok(self) -> Option Source: https://docs.rs/argon2/0.5.3/argon2/type.Result.html?search=Option%3CT%3E%2C+%28T+-%3E+U%29+-%3E+Option%3CU%3E Converts a `Result` into an `Option`, consuming the original `Result` and discarding any error value. ```APIDOC ## pub fn ok(self) -> Option ### Description Converts from `Result` to `Option`. Converts `self` into an `Option`, consuming `self`, and discarding the error, if any. ### Method `ok()` ### Parameters None ### Return Value `Option`: `Some(T)` if the result was `Ok(T)`, `None` if it was `Err(E)`. ### Examples ```rust let x: Result = Ok(2); assert_eq!(x.ok(), Some(2)); let x: Result = Err("Nothing here"); assert_eq!(x.ok(), None); ``` ``` -------------------------------- ### p_cost() Source: https://docs.rs/argon2/0.5.3/src/argon2/params.rs.html?search=std%3A%3Avec Gets the degree of parallelism for the Argon2 algorithm. The value must be between 1 and (2^24)-1, represented as a decimal integer (1 to 3 digits). ```APIDOC ## p_cost() ### Description Gets the degree of parallelism for the Argon2 algorithm. The value must be between 1 and (2^24)-1, represented as a decimal integer (1 to 3 digits). ### Signature `pub const fn p_cost(&self) -> u32` ``` -------------------------------- ### into_ok Source: https://docs.rs/argon2/0.5.3/argon2/type.Result.html?search=Option%3CT%3E%2C+%28T+-%3E+U%29+-%3E+Option%3CU%3E Returns the contained `Ok` value, never panics. This is an experimental API. ```APIDOC ## into_ok ### Description Returns the contained `Ok` value, but never panics. This is a nightly-only experimental API. Unlike `unwrap`, this method is known to never panic on the result types it is implemented for. ### Method `into_ok()` ### Parameters None ### Response - `T`: The contained `Ok` value. ### Constraints Requires `E: Into`. ``` -------------------------------- ### KeyId Methods Source: https://docs.rs/argon2/0.5.3/argon2/struct.KeyId.html?search=std%3A%3Avec Methods for creating and manipulating KeyId instances. ```APIDOC ## KeyId Methods ### `new(slice: &[u8]) -> Result` Create a new KeyId from a slice. ### `from_b64(s: &str) -> Result` Decode KeyId from a B64 string. ### `as_bytes(&self) -> &[u8]` Borrow the inner value as a byte slice. ### `len(&self) -> usize` Get the length in bytes. ### `is_empty(&self) -> bool` Is this value empty? ``` -------------------------------- ### t_cost() Source: https://docs.rs/argon2/0.5.3/src/argon2/params.rs.html?search=std%3A%3Avec Gets the number of iterations for the Argon2 algorithm. The value must be between 1 and (2^32)-1, represented as a decimal integer (1 to 10 digits). ```APIDOC ## t_cost() ### Description Gets the number of iterations for the Argon2 algorithm. The value must be between 1 and (2^32)-1, represented as a decimal integer (1 to 10 digits). ### Signature `pub const fn t_cost(&self) -> u32` ``` -------------------------------- ### Algorithm Methods Source: https://docs.rs/argon2/0.5.3/src/argon2/algorithm.rs.html Provides methods for creating, converting, and retrieving string representations of Argon2 algorithms. ```APIDOC impl Algorithm { /// Parse an [`Algorithm`] from the provided string. pub fn new(id: impl AsRef) -> Result; /// Get the identifier string for this PBKDF2 [`Algorithm`]. pub const fn as_str(&self) -> &'static str; /// Get the [`Ident`] that corresponds to this Argon2 [`Algorithm`]. #[cfg(feature = "password-hash")] #[cfg_attr(docsrs, doc(cfg(feature = "password-hash")))] pub const fn ident(&self) -> Ident<'static>; /// Serialize primitive type as little endian bytes pub(crate) const fn to_le_bytes(self) -> [u8; 4]; } ``` -------------------------------- ### Get Mutable Slice of Words Source: https://docs.rs/argon2/0.5.3/argon2/struct.Block.html Provides mutable access to the underlying 64-bit words of the Block. This allows for in-place modification of the block's data. ```rust fn as_mut(&mut self) -> &mut [u64] ``` -------------------------------- ### Block Loading and Iteration Source: https://docs.rs/argon2/0.5.3/src/argon2/block.rs.html?search= Provides methods for loading data into a `Block` from a byte slice and iterating over its `u64` contents. ```APIDOC ## impl Block ### Methods - **load(&mut self, input: &[u8; Block::SIZE])**: Loads a block from a block-sized byte slice. - **iter(&self)**: Returns an iterator over the `u64` values contained in this block. ``` -------------------------------- ### Get Argon2 Algorithm Identifier String Source: https://docs.rs/argon2/0.5.3/argon2/enum.Algorithm.html?search= Retrieves the static string identifier for a given Argon2 `Algorithm` variant. This is useful for serialization or display purposes. ```rust pub const fn as_str(&self) -> &'static str ``` -------------------------------- ### Unsafe Unwrapping with `unwrap_unchecked` Source: https://docs.rs/argon2/0.5.3/argon2/type.Result.html?search=Option%3CT%3E%2C+%28T+-%3E+U%29+-%3E+Option%3CU%3E Use `unwrap_unchecked` to get the Ok value without checking if it's an Err. This is unsafe and calling it on an Err results in undefined behavior. ```rust let x: Result = Ok(2); assert_eq!(unsafe { x.unwrap_unchecked() }, 2); ``` ```rust let x: Result = Err("emergency failure"); unsafe { x.unwrap_unchecked() }; // Undefined behavior! ``` -------------------------------- ### ParamsBuilder::context Source: https://docs.rs/argon2/0.5.3/argon2/struct.ParamsBuilder.html?search= Creates a new Argon2 context with specified algorithm and version. ```APIDOC ## ParamsBuilder::context ### Description Create a new `Argon2` context using the provided algorithm/version. ### Method `builder.context(algorithm: Algorithm, version: Version) -> Result>` ### Parameters * **algorithm** (Algorithm) - The Argon2 algorithm variant. * **version** (Version) - The Argon2 version. ### Returns A `Result` containing the `Argon2` context if successful, or an `Error` if creation fails. ``` -------------------------------- ### Initialize New Block Source: https://docs.rs/argon2/0.5.3/argon2/struct.Block.html Creates and returns a new Block instance initialized with zeros. This is the default state for a memory block before it's used in Argon2 computations. ```rust pub fn new() -> Self ``` -------------------------------- ### Get Immutable Slice of Words Source: https://docs.rs/argon2/0.5.3/argon2/struct.Block.html Provides immutable access to the underlying 64-bit words of the Block. This allows for reading the block's data without modification. ```rust fn as_ref(&self) -> &[u64] ``` -------------------------------- ### Collecting Results with Error Handling Source: https://docs.rs/argon2/0.5.3/argon2/type.Result.html?search=Option%3CT%3E%2C+%28T+-%3E+U%29+-%3E+Option%3CU%3E Demonstrates collecting results from an iterator where an error condition (underflow) causes the collection to stop and return the error. This example checks for underflow. ```rust let v = vec![1, 2, 0]; let res: Result, &'static str> = v.iter().map(|x: &u32| x.checked_sub(1).ok_or("Underflow!") ).collect(); assert_eq!(res, Err("Underflow!")); ``` -------------------------------- ### Argon2 New Constructor Source: https://docs.rs/argon2/0.5.3/src/argon2/lib.rs.html?search=std%3A%3Avec Initializes a new Argon2 context with specified algorithm, version, and parameters. This constructor allows for custom Argon2 configurations. ```rust pub fn new(algorithm: Algorithm, version: Version, params: Params) -> Self { Self { algorithm, version, params, secret: None, #[cfg(any(target_arch = "x86", target_arch = "x86_64"))] cpu_feat_avx2: avx2_cpuid::init(), } } ``` -------------------------------- ### Unsafe Unwrapping of Error with `unwrap_err_unchecked` Source: https://docs.rs/argon2/0.5.3/argon2/type.Result.html?search=Option%3CT%3E%2C+%28T+-%3E+U%29+-%3E+Option%3CU%3E Use `unwrap_err_unchecked` to get the Err value without checking if it's an Ok. This is unsafe and calling it on an Ok results in undefined behavior. ```rust let x: Result = Ok(2); unsafe { x.unwrap_err_unchecked() }; // Undefined behavior! ``` ```rust let x: Result = Err("emergency failure"); assert_eq!(unsafe { x.unwrap_err_unchecked() }, "emergency failure"); ``` -------------------------------- ### Params::DEFAULT Source: https://docs.rs/argon2/0.5.3/argon2/struct.Params.html?search=Option%3CT%3E%2C+%28T+-%3E+U%29+-%3E+Option%3CU%3E Provides the recommended default Argon2 parameters. ```APIDOC ## `DEFAULT: Self` ### Description Provides the default Argon2 parameters, which are recommended for general use. ``` -------------------------------- ### Block Structure and Initialization Source: https://docs.rs/argon2/0.5.3/src/argon2/block.rs.html?search= Defines the `Block` struct, representing a 1 KiB memory block, and provides methods for initialization. ```APIDOC ## struct Block ### Description Represents a 1 KiB memory block, internally stored as 128 64-bit words. It is aligned to 64 bytes. ### Constants - **SIZE**: `usize` - Memory block size in bytes (1024). ### Methods - **new()**: `const fn() -> Self` - Returns a `Block` initialized with zeros. - **default()**: `Self` - Alias for `new()`, providing a default initialized `Block`. ``` -------------------------------- ### Get a reference to the contained value Source: https://docs.rs/argon2/0.5.3/argon2/type.Result.html?search=Option%3CT%3E%2C+%28T+-%3E+U%29+-%3E+Option%3CU%3E The `as_ref()` method converts a `&Result` into a `Result<&T, &E>`, providing references to the contained values without consuming the original `Result`. ```rust let x: Result = Ok(2); assert_eq!(x.as_ref(), Ok(&2)); let x: Result = Err("Error"); assert_eq!(x.as_ref(), Err(&"Error")); ``` -------------------------------- ### Block Implementations Source: https://docs.rs/argon2/0.5.3/argon2/struct.Block.html Provides details on the constants and methods available for the Block struct. ```APIDOC ## Implementations ### impl Block #### pub const SIZE: usize = 1_024usize Memory block size in bytes #### pub fn new() -> Self Returns a Block initialized with zeros. ``` -------------------------------- ### data Source: https://docs.rs/argon2/0.5.3/src/argon2/params.rs.html?search=Option%3CT%3E%2C+%28T+-%3E+U%29+-%3E+Option%3CU%3E Gets the associated data, which is a byte slice between 0 and 32 bytes in length. Defaults to an empty byte slice. This field is not part of the current Argon2 standard. ```APIDOC ## data ### Description Gets the associated data. This field is not part of the current Argon2 standard and should not be used for non-legacy work. ### Constraints - Byte slice between 0 and 32 bytes in length. - Defaults to an empty byte slice. ### Method Signature `pub fn data(&self) -> &[u8]` ``` -------------------------------- ### Argon2 Debug Implementation Source: https://docs.rs/argon2/0.5.3/src/argon2/lib.rs.html?search=std%3A%3Avec Provides a debug representation for the Argon2 context, showing its algorithm, version, and parameters. This is helpful for inspecting the Argon2 configuration. ```rust impl fmt::Debug for Argon2<'_> { fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> fmt::Result { fmt.debug_struct("Argon2") .field("algorithm", &self.algorithm) .field("version", &self.version) .field("params", &self.params) .finish_non_exhaustive() } } ```