### Password Database Example with PBKDF2 Source: https://docs.rs/ring/latest/ring/pbkdf2/index.html Complete Rust example demonstrating PBKDF2 derivation and verification for a password database. Uses ring::pbkdf2::PBKDF2_HMAC_SHA256, derive, and verify. Includes a salt with user-specific and database-unique components to prevent cross-user and cross-database attacks. The main function shows storing and verifying a password with 100,000 iterations. ```rust use ring::{digest, pbkdf2}; use std::{collections::HashMap, num::NonZeroU32}; static PBKDF2_ALG: pbkdf2::Algorithm = pbkdf2::PBKDF2_HMAC_SHA256; const CREDENTIAL_LEN: usize = digest::SHA256_OUTPUT_LEN; pub type Credential = [u8; CREDENTIAL_LEN]; enum Error { WrongUsernameOrPassword } struct PasswordDatabase { pbkdf2_iterations: NonZeroU32, db_salt_component: [u8; 16], // Normally this would be a persistent database. storage: HashMap, } impl PasswordDatabase { pub fn store_password(&mut self, username: &str, password: &str) { let salt = self.salt(username); let mut to_store: Credential = [0u8; CREDENTIAL_LEN]; pbkdf2::derive(PBKDF2_ALG, self.pbkdf2_iterations, &salt, password.as_bytes(), &mut to_store); self.storage.insert(String::from(username), to_store); } pub fn verify_password(&self, username: &str, attempted_password: &str) -> Result<(), Error> { match self.storage.get(username) { Some(actual_password) => { let salt = self.salt(username); pbkdf2::verify(PBKDF2_ALG, self.pbkdf2_iterations, &salt, attempted_password.as_bytes(), actual_password) .map_err(|_| Error::WrongUsernameOrPassword) }, None => Err(Error::WrongUsernameOrPassword) } } // The salt should have a user-specific component so that an attacker // cannot crack one password for multiple users in the database. It // should have a database-unique component so that an attacker cannot // crack the same user's password across databases in the unfortunate // but common case that the user has used the same password for // multiple systems. fn salt(&self, username: &str) -> Vec { let mut salt = Vec::with_capacity(self.db_salt_component.len() + username.as_bytes().len()); salt.extend(self.db_salt_component.as_ref()); salt.extend(username.as_bytes()); salt } } fn main() { // Normally these parameters would be loaded from a configuration file. let mut db = PasswordDatabase { pbkdf2_iterations: NonZeroU32::new(100_000).unwrap(), db_salt_component: [ // This value was generated from a secure PRNG. 0xd6, 0x26, 0x98, 0xda, 0xf4, 0xdc, 0x50, 0x52, 0x24, 0xf2, 0x27, 0xd1, 0xfe, 0x39, 0x01, 0x8a ], storage: HashMap::new(), }; db.store_password("alice", "@74d7]404j|W}6u"); // An attempt to log in with the wrong password fails. assert!(db.verify_password("alice", "wrong password").is_err()); // Normally there should be an expoentially-increasing delay between // attempts to further protect against online attacks. // An attempt to log in with the right password succeeds. assert!(db.verify_password("alice", "@74d7]404j|W}6u").is_ok()); } ``` -------------------------------- ### Signing and verifying with RSA (PKCS#1 1.5 padding) Source: https://docs.rs/ring/latest/ring/signature/index.html Creates an RSA key pair from DER-encoded private key bytes, signs "hello, world" using PKCS#1 v1.5 padding and SHA256, then verifies the signature with an UnparsedPublicKey. Uses ring::{rand, rsa, signature}. Requires a 2048-bit key (larger supported) and defines MyError and read_file helper. The example returns Result and uses the ? operator, so it must be called from a function returning Result. ```rust use ring::{rand, rsa, signature}; fn sign_and_verify_rsa(private_key_path: &std::path::Path, public_key_path: &std::path::Path) -> Result<(), MyError> { // Create an RSA keypair from the DER-encoded bytes. This example uses // a 2048-bit key, but larger keys are also supported. let private_key_der = read_file(private_key_path)?; let key_pair = rsa::KeyPair::from_der(&private_key_der) .map_err(|_| MyError::BadPrivateKey)?; // Sign the message "hello, world", using PKCS#1 v1.5 padding and the // SHA256 digest algorithm. const MESSAGE: &'static [u8] = b"hello, world"; let rng = rand::SystemRandom::new(); let mut signature = vec![0; key_pair.public().modulus_len()]; key_pair.sign(&signature::RSA_PKCS1_SHA256, &rng, MESSAGE, &mut signature) .map_err(|_| MyError::OOM)?; // Verify the signature. let public_key = signature::UnparsedPublicKey::new(&signature::RSA_PKCS1_2048_8192_SHA256, read_file(public_key_path)?); public_key.verify(MESSAGE, &signature) .map_err(|_| MyError::BadSignature) } #[derive(Debug)] enum MyError { IO(std::io::Error), BadPrivateKey, OOM, BadSignature, } fn read_file(path: &std::path::Path) -> Result, MyError> { use std::io::Read; let mut file = std::fs::File::open(path).map_err(|e| MyError::IO(e))?; let mut contents: Vec = Vec::new(); file.read_to_end(&mut contents).map_err(|e| MyError::IO(e))?; Ok(contents) } ``` -------------------------------- ### Signing and verifying with Ed25519 Source: https://docs.rs/ring/latest/ring/signature/index.html Generates an Ed25519 key pair in PKCS#8 format, signs the message "hello, world", and verifies the signature using an UnparsedPublicKey. Uses ring::signature and requires a random number generator. The example returns Result and uses the ? operator, so it must be called from a function returning Result. ```rust use ring::{ rand, signature::{self, KeyPair}, }; // Generate a key pair in PKCS#8 (v2) format. let rng = rand::SystemRandom::new(); let pkcs8_bytes = signature::Ed25519KeyPair::generate_pkcs8(&rng)?; // Normally the application would store the PKCS#8 file persistently. Later // it would read the PKCS#8 file from persistent storage to use it. let key_pair = signature::Ed25519KeyPair::from_pkcs8(pkcs8_bytes.as_ref())?; // Sign the message "hello, world". const MESSAGE: &[u8] = b"hello, world"; let sig = key_pair.sign(MESSAGE); // Normally an application would extract the bytes of the signature and // send them in a protocol message to the peer(s). Here we just get the // public key key directly from the key pair. let peer_public_key_bytes = key_pair.public_key().as_ref(); // Verify the signature of the message using the public key. Normally the // verifier of the message would parse the inputs to this code out of the // protocol message(s) sent by the signer. let peer_public_key = signature::UnparsedPublicKey::new(&signature::ED25519, peer_public_key_bytes); peer_public_key.verify(MESSAGE, sig.as_ref())?; ``` -------------------------------- ### ECDH key agreement example with X25519 Source: https://docs.rs/ring/latest/ring/agreement/index.html Demonstrates ephemeral key agreement using X25519 with `ring::agreement`. Substitute `agreement::ECDH_P256` or `agreement::ECDH_P384` for NIST curves. Includes key generation, public key computation, unparsed public key creation, and `agree_ephemeral` call. ```rust use ring::{agreement, rand}; let rng = rand::SystemRandom::new(); let my_private_key = agreement::EphemeralPrivateKey::generate(&agreement::X25519, &rng)?; // Make `my_public_key` a byte slice containing my public key. In a real // application, this would be sent to the peer in an encoded protocol // message. let my_public_key = my_private_key.compute_public_key()?; let peer_public_key_bytes = { // In a real application, the peer public key would be parsed out of a // protocol message. Here we just generate one. let peer_private_key = agreement::EphemeralPrivateKey::generate(&agreement::X25519, &rng)?; peer_private_key.compute_public_key()? }; let peer_public_key = agreement::UnparsedPublicKey::new( &agreement::X25519, peer_public_key_bytes); agreement::agree_ephemeral( my_private_key, &peer_public_key, |_key_material| { // In a real application, we'd apply a KDF to the key material and the // public keys (as recommended in RFC 7748) and then derive session // keys from the result. We omit all that here. }, )?; ``` -------------------------------- ### Algorithm Source: https://docs.rs/ring/latest/ring/digest/index.html Represents a digest algorithm. Provides methods to get block length, chaining length, and output length. ```APIDOC ## Algorithm ### Description A digest algorithm. ### Methods - `block_len()` - Returns the block length of the algorithm. - `chaining_len()` - Returns the chaining length of the algorithm. - `output_len()` - Returns the output length of the algorithm. ``` -------------------------------- ### Using the multi-part API Source: https://docs.rs/ring/latest/ring/hmac/index.html?search= Demonstrates the multi-part HMAC API with `Context` for signing data split across multiple parts. Uses HMAC-SHA384 and builds a full message from parts before verification. ```rust use ring::{digest, hmac, rand}; use ring::rand::SecureRandom; let parts = ["hello", ", ", "world"]; // The sender generates a secure key value and signs the message with it. // Note that in a real protocol, a key agreement protocol would be used to // derive `key_value`. let rng = rand::SystemRandom::new(); let mut key_value: [u8; digest::SHA384_OUTPUT_LEN] = rand::generate(&rng)?.expose(); let s_key = hmac::Key::new(hmac::HMAC_SHA384, key_value.as_ref()); let mut s_ctx = hmac::Context::with_key(&s_key); for part in &parts { s_ctx.update(part.as_bytes()); } let tag = s_ctx.sign(); // The receiver (somehow!) knows the key value, and uses it to verify the // integrity of the message. let v_key = hmac::Key::new(hmac::HMAC_SHA384, key_value.as_ref()); let mut msg = Vec::::new(); for part in &parts { msg.extend(part.as_bytes()); } hmac::verify(&v_key, &msg.as_ref(), tag.as_ref())?; ``` -------------------------------- ### public Source: https://docs.rs/ring/latest/ring/rsa/struct.KeyPair.html Returns a reference to the public key. ```APIDOC ## public ### Description Returns a reference to the public key. ### Method public ### Signature pub fn public(&self) -> &PublicKey ### Parameters - **self** (&Self) - Required - The KeyPair instance. ### Return Value - **&PublicKey** - A reference to the public key. ``` -------------------------------- ### Mapping ring::error::Unspecified to custom error type Source: https://docs.rs/ring/latest/ring/error/struct.Unspecified.html Shows how to implement From to map ring errors to a custom error enum, as described in the Rust Book's Error Handling section. The example generates eight random bytes and uses the ? operator to convert errors. ```rust use ring::rand::{self, SecureRandom}; enum Error { CryptoError, IOError(std::io::Error), // [...] } impl From for Error { fn from(_: ring::error::Unspecified) -> Self { Error::CryptoError } } fn eight_random_bytes() -> Result<[u8; 8], Error> { let rng = rand::SystemRandom::new(); let mut bytes = [0; 8]; // The `From` implementation above makes this // equivalent to // `rng.fill(&mut bytes).map_err(|_| Error::CryptoError)?`. rng.fill(&mut bytes)?; Ok(bytes) } assert!(eight_random_bytes().is_ok()); ``` -------------------------------- ### OpeningKey::new Source: https://docs.rs/ring/latest/ring/aead/chacha20_poly1305_openssh/struct.OpeningKey.html Constructs a new OpeningKey from the given key material. ```APIDOC ## OpeningKey::new ### Description Constructs a new `OpeningKey`. ### Method `pub fn new(key_material: &[u8; 64]) -> Self` ### Parameters - `key_material` (`&[u8; 64]`) - Required - The key material for the opening key. ### Returns - `Self` - The newly constructed `OpeningKey`. ``` -------------------------------- ### Statics Source: https://docs.rs/ring/latest/ring/digest/index.html?search= Static instances of digest algorithms for common algorithms. ```APIDOC ## Statics ### Description Static instances of digest algorithms for common algorithms. ### Statics - **SHA1_FOR_LEGACY_USE_ONLY** - SHA-1 as specified in FIPS 180-4. Deprecated. - **SHA256** - SHA-256 as specified in FIPS 180-4. - **SHA384** - SHA-384 as specified in FIPS 180-4. - **SHA512** - SHA-512 as specified in FIPS 180-4. - **SHA512_256** - SHA-512/256 as specified in FIPS 180-4. ``` -------------------------------- ### from_components Source: https://docs.rs/ring/latest/ring/rsa/struct.KeyPair.html Constructs an RSA private key from its big-endian-encoded components. Only two-prime keys are supported, with modulus length between 2047 and 4096 bits. ```APIDOC ## from_components ### Description Constructs an RSA private key from its big-endian-encoded components. Only two-prime keys are supported, with modulus length between 2047 and 4096 bits. ### Method from_components ### Signature pub fn from_components(components: &KeyPairComponents) -> Result where Public: AsRef<[u8]>, Private: AsRef<[u8]>, ### Parameters - **components** (&KeyPairComponents) - Required - The key components. ### Return Value - **Result** - The constructed KeyPair or a KeyRejected error. ### Usage Notes - The public modulus (n) must be at least 2047 bits and no larger than 4096 bits. - The public exponent must be at least 65537 and no more than 33 bits long. - Validation follows NIST SP-800-56B rev. 1 section 6.4.1.4.3 with exceptions. ``` -------------------------------- ### hmac::Context Source: https://docs.rs/ring/latest/ring/hmac/index.html?search=Option%3CT%3E%2C%20(T%20-%3E%20U)%20-%3E%20Option%3CU%3E A context for multi-step (Init-Update-Finish) HMAC signing. Use this when the input data is in multiple parts. ```APIDOC ## hmac::Context ### Description A context for multi-step (Init-Update-Finish) HMAC signing. Use this when the input data is in multiple parts. ### Methods #### with_key `pub fn with_key(key: &Key) -> Self` Creates a new context for multi-step HMAC signing using the given key. #### update `pub fn update(&mut self, data: &[u8])` Updates the context with more data to be signed. #### sign `pub fn sign(self) -> Tag` Finishes the HMAC computation and returns the tag. ### Request Example ```rust use ring::{hmac, rand}; let rng = rand::SystemRandom::new(); let key = hmac::Key::generate(hmac::HMAC_SHA256, &rng)?; let mut ctx = hmac::Context::with_key(&key); ctx.update(b"hello"); ctx.update(b", "); ctx.update(b"world"); let tag = ctx.sign(); ``` ``` -------------------------------- ### BoundKey::new(unbound_key, nonce_sequence) Source: https://docs.rs/ring/latest/ring/aead/struct.OpeningKey.html Constructs a new OpeningKey from an UnboundKey and a NonceSequence. This is the primary way to create an OpeningKey for decryption. ```APIDOC ## BoundKey::new(unbound_key, nonce_sequence) ### Description Constructs a new OpeningKey from an UnboundKey and a NonceSequence. This is the primary way to create an OpeningKey for decryption. ### Method new ### Parameters - **unbound_key** (UnboundKey) - Required - The unbound key material. - **nonce_sequence** (N) - Required - The nonce sequence to use. ### Returns - **Self** - The constructed OpeningKey. ``` -------------------------------- ### Algorithm Source: https://docs.rs/ring/latest/ring/aead/index.html?search=std%3A%3Avec An AEAD Algorithm. ```APIDOC ## Algorithm ### Description An AEAD Algorithm. ``` -------------------------------- ### Convert PEM SubjectPublicKeyInfo to binary RSAPublicKey with openssl Source: https://docs.rs/ring/latest/ring/signature/index.html Converts a PEM-encoded RSA public key in SubjectPublicKeyInfo format ("BEGIN PUBLIC KEY") to the binary RSAPublicKey format needed by verify(). Uses OpenSSL command-line tool with -RSAPublicKey_out and DER output. ```sh openssl rsa -pubin \ -in public_key.pem \ -inform PEM \ -RSAPublicKey_out \ -outform DER \ -out public_key.der ``` -------------------------------- ### Key::new Source: https://docs.rs/ring/latest/ring/hmac/index.html?search= Creates a new HMAC key from a given key value and algorithm. This is a constructor for the Key struct. ```APIDOC ## Key::new ### Description Creates a new HMAC key from a given key value and algorithm. ### Parameters - **algorithm** (Algorithm) - Required - The HMAC algorithm to use. - **key_value** (impl AsRef<[u8]>) - Required - The key value. ### Returns - **Key** - The constructed key. ### Request Example ```rust use ring::{hmac, rand}; let rng = rand::SystemRandom::new(); let key_value: [u8; 32] = rand::generate(&rng)?.expose(); let key = hmac::Key::new(hmac::HMAC_SHA256, key_value.as_ref()); ``` ``` -------------------------------- ### Struct: Tag Source: https://docs.rs/ring/latest/ring/aead/index.html A possibly valid authentication tag. ```APIDOC ## Struct: Tag ### Description A possibly valid authentication tag. ### Type Struct ### Fields - (No fields documented in source) ``` -------------------------------- ### Convert PEM PKCS#8 key to binary PKCS#8 DER format Source: https://docs.rs/ring/latest/ring/rsa/struct.KeyPair.html OpenSSL command to convert a Base64 PEM PKCS#8-encoded key to binary PKCS#8 DER format. The output file is used as input to `KeyPair::from_pkcs8`. ```sh openssl pkcs8 -nocrypt -outform der \ -in rsa-2048-private-key.pem > rsa-2048-private-key.pk8 ``` -------------------------------- ### Generate 2048-bit RSA private key in PKCS#8 DER format Source: https://docs.rs/ring/latest/ring/rsa/struct.KeyPair.html OpenSSL command to generate a 2048-bit RSA private key with public exponent 65537 and output it as an unencrypted PKCS#8 DER file. The output file is used as input to `KeyPair::from_pkcs8`. ```sh openssl genpkey -algorithm RSA \ -pkeyopt rsa_keygen_bits:2048 \ -pkeyopt rsa_keygen_pubexp:65537 | \ openssl pkcs8 -topk8 -nocrypt -outform der > rsa-2048-private-key.pk8 ``` -------------------------------- ### Algorithm Source: https://docs.rs/ring/latest/ring/hkdf/index.html An HKDF algorithm. This struct represents a specific HKDF algorithm configuration. ```APIDOC ## Algorithm ### Description An HKDF algorithm. This struct represents a specific HKDF algorithm configuration. ``` -------------------------------- ### Generate 3072-bit RSA private key in PKCS#8 DER format Source: https://docs.rs/ring/latest/ring/rsa/struct.KeyPair.html OpenSSL command to generate a 3072-bit RSA private key with public exponent 65537 and output it as an unencrypted PKCS#8 DER file. The output file is used as input to `KeyPair::from_pkcs8`. ```sh openssl genpkey -algorithm RSA \ -pkeyopt rsa_keygen_bits:3072 \ -pkeyopt rsa_keygen_pubexp:65537 | \ openssl pkcs8 -topk8 -nocrypt -outform der > rsa-3072-private-key.pk8 ``` -------------------------------- ### Salt::algorithm Source: https://docs.rs/ring/latest/ring/hkdf/struct.Salt.html Returns the algorithm used to derive this salt. This is useful for inspecting the configuration of the salt. ```APIDOC ## Salt::algorithm ### Description Returns the algorithm used to derive this salt. ### Method `pub fn algorithm(&self) -> Algorithm` ### Returns - **Algorithm** - The digest algorithm associated with this salt. ``` -------------------------------- ### Sample Source: https://docs.rs/ring/latest/ring/aead/quic/index.html QUIC sample for new key masks. This type alias represents a sample used in the QUIC header protection key derivation process. ```APIDOC ## Sample ### Description QUIC sample for new key masks. This type alias represents a sample used in the QUIC header protection key derivation process. ### Type Type Alias ### Usage Used as input to the header protection key generation. ``` -------------------------------- ### Static: CHACHA20_POLY1305 Source: https://docs.rs/ring/latest/ring/aead/index.html ChaCha20-Poly1305 as described in RFC 8439. ```APIDOC ## Static: CHACHA20_POLY1305 ### Description ChaCha20-Poly1305 as described in RFC 8439. ### Type Static ### Value (Not specified in source) ``` -------------------------------- ### test_file! Macro Definition Source: https://docs.rs/ring/latest/ring/macro.test_file.html?search= Defines the `test_file!` macro that references a test input file. It is deprecated and will be removed as it is an internal API. ```rust macro_rules! test_file { ($file_name:expr) => { ... }; } ``` -------------------------------- ### Using the one-shot API Source: https://docs.rs/ring/latest/ring/hmac/index.html?search= Shows the one-shot HMAC API where the sender generates a random key value and signs a message, and the receiver uses the same key to verify integrity. Requires `ring::rand::SecureRandom` to expose the generated key value. ```rust use ring::{digest, hmac, rand}; use ring::rand::SecureRandom; let msg = "hello, world"; // The sender generates a secure key value and signs the message with it. // Note that in a real protocol, a key agreement protocol would be used to // derive `key_value`. let rng = rand::SystemRandom::new(); let key_value: [u8; digest::SHA256_OUTPUT_LEN] = rand::generate(&rng)?.expose(); let s_key = hmac::Key::new(hmac::HMAC_SHA256, key_value.as_ref()); let tag = hmac::sign(&s_key, msg.as_bytes()); // The receiver (somehow!) knows the key value, and uses it to verify the // integrity of the message. let v_key = hmac::Key::new(hmac::HMAC_SHA256, key_value.as_ref()); hmac::verify(&v_key, msg.as_bytes(), tag.as_ref())?; ``` -------------------------------- ### Context::algorithm Source: https://docs.rs/ring/latest/ring/digest/struct.Context.html Returns the algorithm that this context is using. ```APIDOC ## Context::algorithm ### Description Returns the algorithm that this context is using. ### Method `pub fn algorithm(&self) -> &'static Algorithm` ### Parameters - **self** - The context. ### Returns - **&'static Algorithm** - The algorithm associated with this context. ### Example ```rust use ring::digest; let ctx = digest::Context::new(&digest::SHA384); let algo = ctx.algorithm(); ``` ``` -------------------------------- ### PublicKey::fmt Source: https://docs.rs/ring/latest/ring/rsa/struct.PublicKey.html Formats the value using the given formatter. This is part of the Debug trait implementation. ```APIDOC ## [RUST] PublicKey::fmt ### Description Formats the value using the given formatter. This is part of the Debug trait implementation. ### Method Rust trait method ### Endpoint `fn fmt(&self, f: &mut Formatter<'_>) -> Result<(), Error>` ### Parameters #### Self - `self` (&PublicKey) - Required - The public key instance. #### Other - `f` (&mut Formatter<'_>) - Required - The formatter to write to. ### Returns - `Result<(), Error>` - Ok if formatting succeeded, otherwise an error. ### Example ```rust let key: PublicKey = ...; println!("{:?}", key); ``` ``` -------------------------------- ### HeaderProtectionKey::new_mask Source: https://docs.rs/ring/latest/ring/aead/quic/struct.HeaderProtectionKey.html Generates a new QUIC Header Protection mask. The sample must be exactly self.algorithm().sample_len() bytes long. ```APIDOC ## HeaderProtectionKey::new_mask ### Description Generates a new QUIC Header Protection mask. The sample must be exactly `self.algorithm().sample_len()` bytes long. ### Method Method ### Signature ```rust pub fn new_mask(&self, sample: &[u8]) -> Result<[u8; 5], Unspecified> ``` ### Parameters - `sample` (`&[u8]`) - Required - The sample bytes, must be exactly `self.algorithm().sample_len()` bytes long. ### Returns - `Result<[u8; 5], Unspecified>` - The 5-byte header protection mask or an error. ``` -------------------------------- ### open_in_place Source: https://docs.rs/ring/latest/ring/aead/struct.OpeningKey.html Authenticates and decrypts ('opens') data in place. The input must be the ciphertext followed by the tag, and on success the plaintext is returned without the tag. ```APIDOC ## open_in_place ### Description Authenticates and decrypts ('opens') data in place. The input must be the ciphertext followed by the tag, and on success the plaintext is returned without the tag. ### Method open_in_place ### Signature pub fn open_in_place<'in_out, A>(&mut self, aad: Aad, in_out: &'in_out mut [u8]) -> Result<&'in_out mut [u8], Unspecified> where A: AsRef<[u8]> ### Parameters - **aad** (Aad) - Required - The additional authenticated data (AAD), if any. - **in_out** (&'in_out mut [u8]) - Required - On input, the ciphertext followed by the tag. On success, overwritten with the plaintext. ### Return Value - **Result<&'in_out mut [u8], Unspecified>** - On success, returns a reference to the plaintext (without the tag). On error, returns `Err(Unspecified)` and `in_out` may have been overwritten in an unspecified way. ``` -------------------------------- ### BoundKey::algorithm() Source: https://docs.rs/ring/latest/ring/aead/struct.OpeningKey.html Returns the AEAD algorithm associated with this OpeningKey. This is useful for identifying the algorithm used for decryption. ```APIDOC ## BoundKey::algorithm() ### Description Returns the AEAD algorithm associated with this OpeningKey. This is useful for identifying the algorithm used for decryption. ### Method algorithm ### Parameters None ### Returns - **&'static Algorithm** - The AEAD algorithm. ``` -------------------------------- ### HeaderProtectionKey::algorithm Source: https://docs.rs/ring/latest/ring/aead/quic/struct.HeaderProtectionKey.html Returns the key's algorithm. ```APIDOC ## HeaderProtectionKey::algorithm ### Description Returns the key's algorithm. ### Method Getter ### Signature ```rust pub fn algorithm(&self) -> &'static Algorithm ``` ### Returns - `&'static Algorithm` - The algorithm associated with this key. ``` -------------------------------- ### LessSafeKey::open_in_place Source: https://docs.rs/ring/latest/ring/aead/struct.LessSafeKey.html Opens data in place using an arbitrary nonce. This method is similar to `OpeningKey::open_in_place` but accepts any nonce. ```APIDOC ## LessSafeKey::open_in_place ### Description Like `super::OpeningKey::open_in_place()`, except it accepts an arbitrary nonce. `nonce` must be unique for every use of the key to open data. ### Method `pub fn open_in_place<'in_out, A>(&self, nonce: Nonce, aad: Aad, in_out: &'in_out mut [u8]) -> Result<&'in_out mut [u8], Unspecified>` ### Parameters - `nonce` (Nonce) - Required - The nonce to use for opening. - `aad` (Aad) - Required - The additional authenticated data. - `in_out` (&mut [u8]) - Required - The input ciphertext and output plaintext buffer. ### Returns - `Result<&'in_out mut [u8], Unspecified>` - The plaintext on success, or an error. ``` -------------------------------- ### Context::with_key Source: https://docs.rs/ring/latest/ring/hmac/struct.Context.html Constructs a new HMAC signing context using the given digest algorithm and key. ```APIDOC ## [Rust] Context::with_key ### Description Constructs a new HMAC signing context using the given digest algorithm and key. ### Method `pub fn with_key(signing_key: &Key) -> Self` ### Parameters - `signing_key` (`&Key`) - The signing key to use for HMAC. ### Returns - `Self` - A new HMAC signing context. ``` -------------------------------- ### SystemRandom::new Source: https://docs.rs/ring/latest/ring/rand/struct.SystemRandom.html Constructs a new SystemRandom instance. This constructor is guaranteed to succeed and has low latency, deferring any initialization to the first call to fill(). ```APIDOC ## SystemRandom::new ### Description Constructs a new `SystemRandom` instance. This constructor is guaranteed to succeed and has low latency, deferring any initialization to the first call to `fill()`. ### Method `new` ### Signature `pub fn new() -> Self` ### Parameters None. ### Returns - `Self` - A new `SystemRandom` instance. ### Example ```rust use ring::rand::SystemRandom; let rng = SystemRandom::new(); ``` ``` -------------------------------- ### UnparsedPublicKey::new Source: https://docs.rs/ring/latest/ring/agreement/struct.UnparsedPublicKey.html Constructs a new UnparsedPublicKey with the given algorithm and bytes. ```APIDOC ## UnparsedPublicKey::new ### Description Constructs a new `UnparsedPublicKey`. ### Method `pub fn new(algorithm: &'static Algorithm, bytes: B) -> Self` ### Parameters - **algorithm** (`&'static Algorithm`) - The algorithm for the public key. - **bytes** (`B`) - The raw bytes of the public key. ### Returns - `Self` - A new `UnparsedPublicKey` instance. ``` -------------------------------- ### Struct: OpeningKey Source: https://docs.rs/ring/latest/ring/aead/index.html An AEAD key for authenticating and decrypting (“opening”), bound to a nonce sequence. ```APIDOC ## Struct: OpeningKey ### Description An AEAD key for authenticating and decrypting (“opening”), bound to a nonce sequence. ### Type Struct ### Fields - (No fields documented in source) ``` -------------------------------- ### LessSafeKey::new Source: https://docs.rs/ring/latest/ring/aead/struct.LessSafeKey.html Constructs a new LessSafeKey from an UnboundKey. This is the constructor for the LessSafeKey type. ```APIDOC ## LessSafeKey::new ### Description Constructs a `LessSafeKey` from an `UnboundKey`. ### Method `pub fn new(key: UnboundKey) -> Self` ### Parameters - `key` (UnboundKey) - Required - The unbound key to wrap. ### Returns - `Self` - The constructed `LessSafeKey`. ``` -------------------------------- ### Algorithm::sample_len Source: https://docs.rs/ring/latest/ring/aead/quic/struct.Algorithm.html Returns the required sample length for the QUIC header protection algorithm. ```APIDOC ## [METHOD] sample_len ### Description Returns the required sample length. ### Method sample_len ### Parameters None ### Response #### Success Response - **usize** - The required sample length. ``` -------------------------------- ### SealingKey::new Source: https://docs.rs/ring/latest/ring/aead/chacha20_poly1305_openssh/struct.SealingKey.html Constructs a new SealingKey from 64 bytes of key material. ```APIDOC ## SealingKey::new ### Description Constructs a new `SealingKey`. ### Method `pub fn new(key_material: &[u8; 64]) -> Self` ### Parameters - **key_material** (`&[u8; 64]`) - Required - The 64-byte key material. ### Returns - `Self` - A new `SealingKey` instance. ``` -------------------------------- ### Key::generate Source: https://docs.rs/ring/latest/ring/hmac/index.html Generates a new HMAC key using the specified algorithm and a secure random number generator. This is a constructor for the Key struct. ```APIDOC ## Key::generate ### Description Generates a new HMAC key using the specified algorithm and a secure random number generator. ### Function Signature `Key::generate(algorithm: Algorithm, rng: &dyn SecureRandom) -> Result` ### Parameters - **algorithm** (Algorithm) - Required - The HMAC algorithm to use (e.g., HMAC_SHA256). - **rng** (SecureRandom) - Required - A secure random number generator. ### Returns - **Result** - The generated key or an error. ### Example ```rust use ring::{hmac, rand}; let rng = rand::SystemRandom::new(); let key = hmac::Key::generate(hmac::HMAC_SHA256, &rng)?; ``` ``` -------------------------------- ### Convert PEM RSA private key to PKCS#8 DER format Source: https://docs.rs/ring/latest/ring/rsa/struct.KeyPair.html OpenSSL command to convert a Base64 PEM RSA private key (without PKCS#8 wrapper) to binary PKCS#8 DER format. The output file is used as input to `KeyPair::from_pkcs8`. ```sh openssl pkcs8 -topk8 -nocrypt -outform der \ -in rsa-2048-private-key.pem > rsa-2048-private-key.pk8 ``` -------------------------------- ### PublicKey::from (From<&PublicKey> for PublicKeyComponents) Source: https://docs.rs/ring/latest/ring/rsa/struct.PublicKey.html Converts a reference to a PublicKey into a PublicKeyComponents instance. This is part of the From trait implementation. ```APIDOC ## [RUST] PublicKey::from (From<&PublicKey> for PublicKeyComponents) ### Description Converts a reference to a PublicKey into a PublicKeyComponents instance. This is part of the From trait implementation. ### Method Rust trait method ### Endpoint `fn from(public_key: &PublicKey) -> Self` ### Parameters #### Other - `public_key` (&PublicKey) - Required - The public key to convert. ### Returns - `Self` - A PublicKeyComponents instance. ### Example ```rust let key: PublicKey = ...; let components: PublicKeyComponents> = PublicKeyComponents::from(&key); ``` ``` -------------------------------- ### Context Source: https://docs.rs/ring/latest/ring/digest/index.html A context for multi-step (Init-Update-Finish) digest calculations. This allows incremental hashing when data is not available in a single contiguous slice. ```APIDOC ## Context ### Description A context for multi-step (Init-Update-Finish) digest calculations. ### Usage Use this struct when data is not available in a single contiguous slice. Initialize with an algorithm, update with data chunks, and finish to obtain the digest. ``` -------------------------------- ### verify Source: https://docs.rs/ring/latest/ring/pbkdf2/fn.verify.html Verifies that a previously-derived PBKDF2 value matches the PBKDF2 value derived from the other inputs. The comparison is done in constant time to prevent timing attacks. ```APIDOC ## Function verify ### Description Verifies that a previously-derived (e.g., using `derive`) PBKDF2 value matches the PBKDF2 value derived from the other inputs. The comparison is done in constant time to prevent timing attacks. The comparison will fail if `previously_derived` is empty (has a length of zero). ### Signature ```rust pub fn verify( algorithm: Algorithm, iterations: NonZeroU32, salt: &[u8], secret: &[u8], previously_derived: &[u8], ) -> Result<(), Unspecified> ``` ### Parameters - **algorithm** (Algorithm) - Required - The PRF (HMAC with the given digest algorithm). - **iterations** (NonZeroU32) - Required - The iteration count (c in RFC 2898 Section 5.2). - **salt** (&[u8]) - Required - The salt (S in RFC 2898 Section 5.2). - **secret** (&[u8]) - Required - The password (P in RFC 2898 Section 5.2). - **previously_derived** (&[u8]) - Required - The derived key (dk in RFC 2898 Section 5.2). Its length determines the derived key length (dkLen). ### Return Value - **Result<(), Unspecified>** - Returns `Ok(())` if the derived value matches, or `Err(Unspecified)` if it does not match or if `previously_derived` is empty. ### Notes - The comparison is performed in constant time to prevent timing attacks. - The function will fail if `previously_derived` has a length of zero. ``` -------------------------------- ### from_der Source: https://docs.rs/ring/latest/ring/rsa/struct.KeyPair.html Parses an RSA private key that is not inside a PKCS#8 wrapper. The key must be DER-encoded ASN.1 RSAPrivateKey as described in RFC 3447 Appendix A.1.2. ```APIDOC ## from_der ### Description Parses an RSA private key that is not inside a PKCS#8 wrapper. The key must be DER-encoded ASN.1 RSAPrivateKey as described in RFC 3447 Appendix A.1.2. ### Method from_der ### Signature pub fn from_der(input: &[u8]) -> Result ### Parameters - **input** (&[u8]) - Required - The DER-encoded RSAPrivateKey. ### Return Value - **Result** - The parsed KeyPair or a KeyRejected error. ### Usage Notes - It is recommended to use `from_pkcs8()` instead. - See the documentation for `from_components` for validation details. ``` -------------------------------- ### verify Source: https://docs.rs/ring/latest/ring/signature/index.html Verifies a signature using the specified algorithm. The algorithm is identified by passing a reference to the algorithm object, and the function returns a Result indicating whether the signature is valid. ```APIDOC ## verify ### Description Verifies a signature using the specified algorithm. The algorithm is identified by passing a reference to the algorithm object, and the function returns a Result indicating whether the signature is valid. ### Method Function call ### Signature `verify(public_key, message, signature, algorithm)` ### Parameters - **public_key** (PublicKey) - Required - The public key used for verification. - **message** (bytes) - Required - The message that was signed. - **signature** (bytes) - Required - The signature to verify. - **algorithm** (Algorithm) - Required - The algorithm to use for verification. ### Returns - **Result** - `Ok(())` if the signature is valid, `Err(Unspecified)` otherwise. ``` -------------------------------- ### Algorithm::len (KeyType) Source: https://docs.rs/ring/latest/ring/hkdf/struct.Algorithm.html?search=std%3A%3Avec Returns the length that `Prk::expand()` should expand its input to. ```APIDOC ## Algorithm::len (KeyType) ### Description Returns the length that `Prk::expand()` should expand its input to. ### Method len ### Signature fn len(&self) -> usize ### Parameters None ### Returns - **usize** - The length that `Prk::expand()` should expand its input to. ``` -------------------------------- ### PublicKey::clone_from Source: https://docs.rs/ring/latest/ring/rsa/struct.PublicKey.html Performs copy-assignment from `source`. This is part of the Clone trait implementation. ```APIDOC ## [RUST] PublicKey::clone_from ### Description Performs copy-assignment from `source`. This is part of the Clone trait implementation. ### Method Rust trait method ### Endpoint `fn clone_from(&mut self, source: &Self)` ### Parameters #### Self - `self` (&mut PublicKey) - Required - The destination public key instance. #### Other - `source` (&PublicKey) - Required - The source public key to copy from. ### Returns - `()` - No return value. ### Example ```rust let mut key: PublicKey = ...; let other: PublicKey = ...; key.clone_from(&other); ``` ``` -------------------------------- ### HeaderProtectionKey::new Source: https://docs.rs/ring/latest/ring/aead/quic/struct.HeaderProtectionKey.html Creates a new header protection key for QUIC. The key_bytes must be exactly algorithm.key_len bytes long. ```APIDOC ## HeaderProtectionKey::new ### Description Creates a new header protection key for QUIC. The key_bytes must be exactly algorithm.key_len bytes long. ### Method Constructor ### Signature ```rust pub fn new(algorithm: &'static Algorithm, key_bytes: &[u8]) -> Result ``` ### Parameters - `algorithm` (`&'static Algorithm`) - Required - The algorithm to use. - `key_bytes` (`&[u8]`) - Required - The key bytes, must be exactly `algorithm.key_len` bytes long. ### Returns - `Result` - The new header protection key or an error. ``` -------------------------------- ### Key::generate Source: https://docs.rs/ring/latest/ring/hmac/index.html?search= Generates a new random HMAC key using the specified algorithm and a secure random number generator. This is a constructor for the Key struct. ```APIDOC ## Key::generate ### Description Generates a new random HMAC key using the specified algorithm and a secure random number generator. ### Parameters - **algorithm** (Algorithm) - Required - The HMAC algorithm to use. - **rng** (&dyn SecureRandom) - Required - A secure random number generator. ### Returns - **Result** - The generated key or an error. ### Request Example ```rust use ring::{hmac, rand}; let rng = rand::SystemRandom::new(); let key = hmac::Key::generate(hmac::HMAC_SHA256, &rng)?; ``` ``` -------------------------------- ### KeyType Source: https://docs.rs/ring/latest/ring/hkdf/index.html The length of the OKM (Output Keying Material) for a `Prk::expand()` call. This trait defines the output length for the expand operation. ```APIDOC ## KeyType ### Description The length of the OKM (Output Keying Material) for a `Prk::expand()` call. This trait defines the output length for the expand operation. ``` -------------------------------- ### Signing a value and verifying it wasn't tampered with Source: https://docs.rs/ring/latest/ring/hmac/index.html?search= Generates an HMAC-SHA256 key using a secure random number generator, signs a message, and verifies the tag to ensure the message wasn't tampered with. Uses the module-level `sign` and `verify` functions for one-shot operations. ```rust use ring::{hmac, rand}; let rng = rand::SystemRandom::new(); let key = hmac::Key::generate(hmac::HMAC_SHA256, &rng)?; let msg = "hello, world"; let tag = hmac::sign(&key, msg.as_bytes()); // [We give access to the message to an untrusted party, and they give it // back to us. We need to verify they didn't tamper with it.] hmac::verify(&key, msg.as_bytes(), tag.as_ref())?; ``` -------------------------------- ### Convert PEM PKCS#8 key to binary DER with OpenSSL Source: https://docs.rs/ring/latest/ring/signature/type.RsaKeyPair.html?search= Converts a Base64 PEM PKCS#8-encoded RSA private key to binary DER format using OpenSSL. This is for keys that already have the PKCS#8 wrapper. ```sh openssl pkcs8 -nocrypt -outform der \ -in rsa-2048-private-key.pem > rsa-2048-private-key.pk8 ``` -------------------------------- ### HKDF_SHA1_FOR_LEGACY_USE_ONLY Source: https://docs.rs/ring/latest/ring/hkdf/index.html An HKDF algorithm using HMAC-SHA-1. This is marked as obsolete and should only be used for legacy compatibility. ```APIDOC ## HKDF_SHA1_FOR_LEGACY_USE_ONLY ### Description An HKDF algorithm using HMAC-SHA-1. This is marked as obsolete and should only be used for legacy compatibility. ### Type Static constant of type `Algorithm`. ``` -------------------------------- ### Struct: Nonce Source: https://docs.rs/ring/latest/ring/aead/index.html A nonce for a single AEAD opening or sealing operation. ```APIDOC ## Struct: Nonce ### Description A nonce for a single AEAD opening or sealing operation. ### Type Struct ### Fields - (No fields documented in source) ``` -------------------------------- ### SecureRandom::fill Source: https://docs.rs/ring/latest/ring/rand/struct.SystemRandom.html Fills the provided buffer with random bytes from the operating system. This method may block on the first call due to deferred initialization, so it is recommended to call it once at a non-latency-sensitive time. ```APIDOC ## SecureRandom::fill ### Description Fills the provided buffer with random bytes from the operating system. This method may block on the first call due to deferred initialization, so it is recommended to call it once at a non-latency-sensitive time. ### Method `fill` ### Signature `fn fill(&self, dest: &mut [u8]) -> Result<(), Unspecified>` ### Parameters - `dest` (`&mut [u8]`) - Required - The buffer to fill with random bytes. ### Returns - `Result<(), Unspecified>` - `Ok(())` on success, or an `Unspecified` error on failure. ### Example ```rust use ring::rand::{SecureRandom, SystemRandom}; let rng = SystemRandom::new(); let mut buf = [0u8; 32]; rng.fill(&mut buf).unwrap(); ``` ```