### expect examples Source: https://docs.rs/openssl-sys/0.9.117/openssl_sys/type.OSSL_PASSPHRASE_CALLBACK.html Shows how to use expect to get the contained Some value, with a custom panic message. The first example shows a successful case. The second shows a panic when the value is None. The third shows a recommended message style that describes the reason you expect the Option to be Some. ```rust let x = Some("value"); assert_eq!(x.expect("fruits are healthy"), "value"); ``` ```rust let x: Option<&str> = None; x.expect("fruits are healthy"); // panics with `fruits are healthy` ``` ```rust let item = slice.get(0) .expect("slice should not be empty"); ``` -------------------------------- ### get() example Source: https://docs.rs/openssl/latest/openssl/string/struct.OpensslString.html Example for the `get` method from `Deref`. Returns a subslice of the string, returning `None` on invalid indices. ```rust let v = String::from("🗻∈🌏"); assert_eq!(Some("🗻"), v.get(0..4)); // indices not on UTF-8 sequence boundaries assert!(v.get(1..).is_none()); assert!(v.get(..8).is_none()); // out of bounds assert!(v.get(..42).is_none()); ``` -------------------------------- ### unwrap_or_default example (partial) Source: https://docs.rs/openssl-sys/0.9.117/openssl_sys/type.tls_session_ticket_ext_cb_fn.html Partial example for unwrap_or_default; the source is truncated. ```rust let x: Option = None; let y: Option = Some(12); ``` -------------------------------- ### first() example Source: https://docs.rs/openssl/latest/openssl/hash/struct.DigestBytes.html Shows how to get the first element of a slice using `first()`. The example asserts that the first element of `[10, 40, 30]` is `Some(&10)` and that an empty slice returns `None`. ```rust let v = [10, 40, 30]; assert_eq!(Some(&10), v.first()); let w: &[i32] = &[]; assert_eq!(None, w.first()); ``` -------------------------------- ### Option::take example Source: https://docs.rs/openssl-sys/0.9.117/openssl_sys/type.tls_session_ticket_ext_cb_fn.html Demonstrates `Option::take` removing the value and leaving `None` in its place. The example covers both `Some` and `None` cases. ```rust let mut x = Some(2); let y = x.take(); assert_eq!(x, None); assert_eq!(y, Some(2)); let mut x: Option = None; let y = x.take(); assert_eq!(x, None); assert_eq!(y, None); ``` -------------------------------- ### split_first() example Source: https://docs.rs/openssl/latest/openssl/hash/struct.DigestBytes.html Shows how to split a slice into its first element and the rest using `split_first()`. The example asserts that the first element is `&0` and the rest is `&[1, 2]`. ```rust let x = &[0, 1, 2]; if let Some((first, elements)) = x.split_first() { assert_eq!(first, &0); assert_eq!(elements, &[1, 2]); } ``` -------------------------------- ### EcKey::from_public_key example Source: https://docs.rs/openssl/latest/src/openssl/ec.rs.html Constructs an EC public key from a group and point, then verifies it with check_key(). The example is a doc-test snippet that returns Ok(()) on success. ```rust /// let key = EcKey::from_public_key(&group, &point)?; /// key.check_key()?; /// # Ok(()) } /// ``` ``` -------------------------------- ### X509_STORE_CTX_init Source: https://docs.rs/openssl-sys/0.9.117/src/openssl_sys/handwritten/x509_vfy.rs.html Initializes a X509_STORE_CTX with a store, certificate, and chain. ```APIDOC ## X509_STORE_CTX_init ### Description Initializes a X509_STORE_CTX with a store, certificate, and chain. ### Method FFI Function ### Signature ```rust pub fn X509_STORE_CTX_init( ctx: *mut X509_STORE_CTX, store: *mut X509_STORE, x509: *mut X509, chain: *mut stack_st_X509, ) -> c_int; ``` ### Parameters - **ctx** (*mut X509_STORE_CTX) - Required - Pointer to the context to initialize. - **store** (*mut X509_STORE) - Required - Pointer to the store. - **x509** (*mut X509) - Required - Pointer to the certificate to verify. - **chain** (*mut stack_st_X509) - Required - Pointer to the certificate chain. ### Return Value - **c_int** - 1 on success, 0 on failure. ``` -------------------------------- ### new() Source: https://docs.rs/openssl/latest/openssl/x509/store/struct.X509StoreBuilder.html Creates a new X509StoreBuilder instance for constructing an X509Store. ```APIDOC ## new() ### Description Returns a builder for a certificate store. The store is initially empty. ### Method new ### Parameters None ### Returns Result ### Notes This corresponds to `X509_STORE_new`. ``` -------------------------------- ### len() example Source: https://docs.rs/openssl/latest/openssl/hash/struct.DigestBytes.html Shows how to get the number of elements in a slice using `len()`. The example asserts that the length of `[1, 2, 3]` is 3. ```rust let a = [1, 2, 3]; assert_eq!(a.len(), 3); ``` -------------------------------- ### X509StoreContextRef::init Source: https://docs.rs/openssl/latest/src/openssl/x509/mod.rs.html Initializes an X509 store context with a trust store, certificate, and certificate chain, then runs a closure with the initialized context. ```APIDOC ## X509StoreContextRef::init ### Description Initializes the X509 store context with a trust store, certificate, and certificate chain, then invokes a closure with the initialized context. The context is automatically cleaned up after the closure returns. ### Method init ### Parameters - **trust** (`&store::X509StoreRef`) - Required - The trust store to use for verification. - **cert** (`&X509Ref`) - Required - The certificate to verify. - **cert_chain** (`&StackRef`) - Required - The certificate chain associated with the certificate. - **with_context** (`F`) - Required - A closure that receives a mutable reference to the initialized `X509StoreContextRef` and returns a `Result`. ### Returns - `Result` - The result of the closure, or an error if initialization fails. ### Example ```rust let mut ctx = X509StoreContext::new()?; let result = ctx.init(&trust, &cert, &chain, |ctx| { // use ctx Ok(()) })?; ``` ``` -------------------------------- ### and_then examples Source: https://docs.rs/openssl-sys/0.9.117/openssl_sys/type.tls_session_ticket_ext_cb_fn.html Two examples of and_then: one chaining a fallible function that can overflow, and one using a 2D array to chain get operations. ```rust fn sq_then_to_string(x: u32) -> Option { x.checked_mul(x).map(|sq| sq.to_string()) } assert_eq!(Some(2).and_then(sq_then_to_string), Some(4.to_string())); assert_eq!(Some(1_000_000).and_then(sq_then_to_string), None); // overflowed! assert_eq!(None.and_then(sq_then_to_string), None); ``` ```rust let arr_2d = [["A0", "A1"], ["B0", "B1"]]; let item_0_1 = arr_2d.get(0).and_then(|row| row.get(1)); assert_eq!(item_0_1, Some(&"A1")); let item_2_0 = arr_2d.get(2).and_then(|row| row.get(0)); assert_eq!(item_2_0, None); ``` -------------------------------- ### init Source: https://docs.rs/openssl/latest/openssl/x509/struct.X509StoreContextRef.html Initializes the context with a certificate, chain, and store, then invokes a closure with the prepared context. ```APIDOC ## init(&mut self, trust: &X509StoreRef, cert: &X509Ref, cert_chain: &StackRef, with_context: F) -> Result where F: FnOnce(&mut X509StoreContextRef) -> Result ### Description Initializes this context with the given certificate, certificates chain and certificate store. After initializing the context, the `with_context` closure is called with the prepared context. As long as the closure is running, the context stays initialized and can be used to e.g. verify a certificate. The context will be cleaned up, after the closure finished. ### Method N/A (Rust method) ### Endpoint N/A ### Parameters - **trust** (`&X509StoreRef`) - Required - The certificate store with the trusted certificates. - **cert** (`&X509Ref`) - Required - The certificate that should be verified. - **cert_chain** (`&StackRef`) - Required - The certificates chain. - **with_context** (`F`) - Required - The closure that is called with the initialized context. ### Returns - `Result` - The result of the closure, or an error if initialization fails. ### Notes This corresponds to `X509_STORE_CTX_init` before calling `with_context` and to `X509_STORE_CTX_cleanup` after calling `with_context`. ``` -------------------------------- ### Get integer representation of a Nid Source: https://docs.rs/openssl/latest/openssl/nid/struct.Nid.html Shows how to use Nid::as_raw() to get the integer value of a Nid. The example asserts that Nid::AES_256_GCM.as_raw() equals 901. ```rust use openssl::nid::Nid; assert!(Nid::AES_256_GCM.as_raw() == 901); ``` -------------------------------- ### build(self) Source: https://docs.rs/openssl/latest/openssl/x509/store/struct.X509StoreBuilder.html Consumes the builder and returns the constructed X509Store. ```APIDOC ## build(self) ### Description Constructs the X509Store from the builder. ### Method build ### Parameters - **self** (X509StoreBuilder) - Required - The builder to consume. ### Returns X509Store ``` -------------------------------- ### Example: as_mut Source: https://docs.rs/openssl-sys/0.9.117/openssl_sys/type.tls_session_ticket_ext_cb_fn.html Demonstrates `Option::as_mut` to get a mutable reference to the inner value. The example mutates the value inside the `Some` variant via the mutable reference. ```rust let mut x = Some(2); match x.as_mut() { Some(v) => *v = 42, None => {}, } assert_eq!(x, Some(42)); ``` -------------------------------- ### utf8_chunks iterator output example Source: https://docs.rs/openssl/latest/openssl/hash/struct.DigestBytes.html Shows the expected output of an iterator over UTF-8 chunks, yielding Range values with start and end indices. The example is from the documentation of the utf8_chunks method. ```rust assert_eq!(iter.next(), Some(Range { start: 0, end: 0 })); assert_eq!(iter.next(), Some(Range { start: 1, end: 3 })); assert_eq!(iter.next(), Some(Range { start: 4, end: 4 })); assert_eq!(iter.next(), Some(Range { start: 5, end: 6 })); ``` -------------------------------- ### EVP_OpenInit Source: https://docs.rs/openssl-sys/0.9.117/openssl_sys/fn.EVP_OpenInit.html Documentation for the EVP_OpenInit function from the openssl-sys crate. ```APIDOC ## EVP_OpenInit ### Description Initializes a cipher context for decryption using an ephemeral key and IV, typically for enveloped data. This function is part of the OpenSSL EVP interface. ### Signature ```rust pub unsafe extern "C" fn EVP_OpenInit( ctx: *mut EVP_CIPHER_CTX, type_: *const EVP_CIPHER, ek: *const c_uchar, ekl: c_int, iv: *const c_uchar, priv_: *mut EVP_PKEY, ) -> c_int ``` ### Parameters - **ctx** (`*mut EVP_CIPHER_CTX`) - Required - Pointer to the cipher context to initialize. - **type_** (`*const EVP_CIPHER`) - Required - Pointer to the cipher algorithm to use. - **ek** (`*const c_uchar`) - Required - Pointer to the encrypted key material. - **ekl** (`c_int`) - Required - Length of the encrypted key material. - **iv** (`*const c_uchar`) - Required - Pointer to the initialization vector. - **priv_** (`*mut EVP_PKEY`) - Required - Pointer to the private key used for decryption. ### Return Value - **c_int** - Returns 1 on success, 0 on failure. ``` -------------------------------- ### sign_init Source: https://docs.rs/openssl/latest/src/openssl/pkey_ctx.rs.html Prepares the context for signing using the private key. This must be called before sign. ```APIDOC ## sign_init ### Description Prepares the context for signing using the private key. ### Method `pub fn sign_init(&mut self) -> Result<(), ErrorStack>` ### Parameters None. ### Returns - `Result<(), ErrorStack>` - Ok(()) on success, or an error. ``` -------------------------------- ### substr_range example Source: https://docs.rs/openssl/latest/openssl/string/struct.OpensslString.html Shows how to use `substr_range` to get the range of each substring from a split iterator. ```rust use core::range::Range; let data = "a, b, b, a"; let mut iter = data.split(", ").map(|s| data.substr_range(s).unwrap()); assert_eq!(iter.next(), Some(Range { start: 0, end: 1 })); assert_eq!(iter.next(), Some(Range { start: 3, end: 4 })); assert_eq!(iter.next(), Some(Range { start: 6, end: 7 })); assert_eq!(iter.next(), Some(Range { start: 9, end: 10 })); ``` -------------------------------- ### Client and server SSL/TLS examples using SslConnector and SslAcceptor Source: https://docs.rs/openssl/latest/src/openssl/ssl/mod.rs.html Two examples from the module documentation: the first connects as a client to a remote server using SslConnector, and the second accepts connections as a server using SslAcceptor. Both use SslMethod::tls() and require OpenSSL initialization. ```rust use openssl::ssl::{SslMethod, SslConnector}; use std::io::{Read, Write}; use std::net::TcpStream; let connector = SslConnector::builder(SslMethod::tls()).unwrap().build(); let stream = TcpStream::connect("google.com:443").unwrap(); let mut stream = connector.connect("google.com", stream).unwrap(); stream.write_all(b"GET / HTTP/1.0\r\n\r\n").unwrap(); let mut res = vec![]; stream.read_to_end(&mut res).unwrap(); println!("{}", String::from_utf8_lossy(&res)); ``` ```rust use openssl::ssl::{SslMethod, SslAcceptor, SslStream, SslFiletype}; use std::net::{TcpListener, TcpStream}; use std::sync::Arc; use std::thread; let mut acceptor = SslAcceptor::mozilla_intermediate(SslMethod::tls()).unwrap(); acceptor.set_private_key_file("key.pem", SslFiletype::PEM).unwrap(); acceptor.set_certificate_chain_file("certs.pem").unwrap(); acceptor.check_private_key().unwrap(); let acceptor = Arc::new(acceptor.build()); let listener = TcpListener::bind("0.0.0.0:8443").unwrap(); fn handle_client(stream: SslStream) { // ... } for stream in listener.incoming() { match stream { Ok(stream) => { let acceptor = acceptor.clone(); thread::spawn(move || { let stream = acceptor.accept(stream).unwrap(); handle_client(stream); }); } Err(e) => { /* connection failed */ } } } ``` -------------------------------- ### as_simd example Source: https://docs.rs/openssl/latest/openssl/hash/struct.DigestBytes.html Demonstrates the nightly-only as_simd method with portable_simd. Shows splitting a slice into prefix, SIMD middle, and suffix, and a basic_simd_sum function that sums f32 values using SIMD. ```rust #![feature(portable_simd)] use core::simd::prelude::*; let short = &[1, 2, 3]; let (prefix, middle, suffix) = short.as_simd::<4>(); assert_eq!(middle, []); // Not enough elements for anything in the middle // They might be split in any possible way between prefix and suffix let it = prefix.iter().chain(suffix).copied(); assert_eq!(it.collect::>(), vec![1, 2, 3]); fn basic_simd_sum(x: &[f32]) -> f32 { use std::ops::Add; let (prefix, middle, suffix) = x.as_simd(); let sums = f32x4::from_array([ prefix.iter().copied().sum(), 0.0, 0.0, suffix.iter().copied().sum(), ]); let sums = middle.iter().copied().fold(sums, f32x4::add); sums.reduce_sum() } ``` -------------------------------- ### first_mut() example Source: https://docs.rs/openssl/latest/openssl/hash/struct.DigestBytes.html Shows how to get a mutable reference to the first element using `first_mut()`. The example modifies the first element and asserts the result. It also shows that an empty slice returns `None`. ```rust let x = &mut [0, 1, 2]; if let Some(first) = x.first_mut() { *first = 5; } assert_eq!(x, &[5, 1, 2]); let y: &mut [i32] = &mut []; assert_eq!(None, y.first_mut()); ``` -------------------------------- ### keygen_init Source: https://docs.rs/openssl/latest/src/openssl/pkey_ctx.rs.html Prepares the context for key generation. ```APIDOC ## keygen_init ### Description Prepares the context for key generation. ### Method `pub fn keygen_init(&mut self) -> Result<(), ErrorStack>` ### Parameters None. ### Returns - `Result<(), ErrorStack>` - Ok(()) on success, or an error. ``` -------------------------------- ### get: element or subslice Source: https://docs.rs/openssl/latest/openssl/hash/struct.DigestBytes.html Shows the `get` method, which returns a reference to an element or subslice depending on the index type. The example covers a position, a range, an out-of-bounds position, and an out-of-bounds range, all returning `Option`. ```rust let v = [10, 40, 30]; assert_eq!(Some(&40), v.get(1)); assert_eq!(Some(&[10, 40][..]), v.get(0..2)); assert_eq!(None, v.get(3)); assert_eq!(None, v.get(0..4)); ``` -------------------------------- ### paramgen_init Source: https://docs.rs/openssl/latest/src/openssl/pkey_ctx.rs.html Prepares the context for key parameter generation. ```APIDOC ## paramgen_init ### Description Prepares the context for key parameter generation. ### Method `pub fn paramgen_init(&mut self) -> Result<(), ErrorStack>` ### Parameters None. ### Returns - `Result<(), ErrorStack>` - Ok(()) on success, or an error. ``` -------------------------------- ### starts_with: check if slice starts with a prefix Source: https://docs.rs/openssl/latest/openssl/hash/struct.DigestBytes.html Use to check if a slice starts with a given prefix. Returns true if the needle is a prefix or equal to the slice. The example asserts various true and false cases. ```rust let v = [10, 40, 30]; assert!(v.starts_with(&[10])); assert!(v.starts_with(&[10, 40])); assert!(v.starts_with(&v)); assert!(!v.starts_with(&[50])); assert!(!v.starts_with(&[10, 50])); ``` -------------------------------- ### Key wrapping and unwrapping example Source: https://docs.rs/openssl/latest/openssl/aes/index.html Demonstrates wrapping and unwrapping a key using wrap_key and unwrap_key functions with AesKey. The example uses a key encryption key (KEK) and a key to wrap, then verifies the unwrapped key matches the original. ```rust use openssl::aes::{AesKey, unwrap_key, wrap_key}; let kek = b"\x00\x01\x02\x03\x04\x05\x06\x07\x08\x09\x0A\x0B\x0C\x0D\x0E\x0F"; let key_to_wrap = b"\x00\x11\x22\x33\x44\x55\x66\x77\x88\x99\xAA\xBB\xCC\xDD\xEE\xFF"; let enc_key = AesKey::new_encrypt(kek).unwrap(); let mut ciphertext = [0u8; 24]; wrap_key(&enc_key, None, &mut ciphertext, &key_to_wrap[..]).unwrap(); let dec_key = AesKey::new_decrypt(kek).unwrap(); let mut orig_key = [0u8; 16]; unwrap_key(&dec_key, None, &mut orig_key, &ciphertext[..]).unwrap(); assert_eq!(&orig_key[..], &key_to_wrap[..]); ``` -------------------------------- ### as_chunks: split slice into N-element chunks from start Source: https://docs.rs/openssl/latest/openssl/hash/struct.DigestBytes.html Splits a slice into N-element chunks from the start, returning a remainder shorter than N. The example shows a slice of length 5 split into 2-element chunks with a remainder of one element. ```rust let slice = ['l', 'o', 'r', 'e', 'm']; let (chunks, remainder) = slice.as_chunks(); assert_eq!(chunks, &[['l', 'o'], ['r', 'e']]); assert_eq!(remainder, &['m']); ``` -------------------------------- ### as_rchunks: split slice into N-element chunks from end Source: https://docs.rs/openssl/latest/openssl/hash/struct.DigestBytes.html Splits a slice into N-element chunks starting from the end, returning a remainder shorter than N. The example shows a slice of length 5 split into 2-element chunks with a remainder of one element at the start. ```rust let slice = ['l', 'o', 'r', 'e', 'm']; let (remainder, chunks) = slice.as_rchunks(); assert_eq!(remainder, &['l']); assert_eq!(chunks, &[['o', 'r'], ['e', 'm']]); ``` -------------------------------- ### first_chunk::() example Source: https://docs.rs/openssl/latest/openssl/hash/struct.DigestBytes.html Shows how to get the first N items of a slice as an array using `first_chunk::()`. The example asserts that a slice of length 3 returns `Some(&[10, 40])` for N=2, a slice of length 1 returns `None` for N=2, and an empty slice returns `Some(&[])` for N=0. ```rust let u = [10, 40, 30]; assert_eq!(Some(&[10, 40]), u.first_chunk::<2>()); let v: &[i32] = &[10]; assert_eq!(None, v.first_chunk::<2>()); let w: &[i32] = &[]; assert_eq!(Some(&[]), w.first_chunk::<0>()); ``` -------------------------------- ### Build::new Source: https://docs.rs/openssl-src/300.6.1%2B3.6.3/openssl_src/struct.Build.html Creates a new Build instance for configuring and building OpenSSL. ```APIDOC ## Build::new ### Description Creates a new `Build` instance for configuring and building OpenSSL. ### Method `pub fn new() -> Build` ### Parameters None. ### Returns - `Build` - A new `Build` instance. ``` -------------------------------- ### LibCtx::new Source: https://docs.rs/openssl/latest/openssl/lib_ctx/struct.LibCtx.html Documentation for the `LibCtx::new` constructor, which creates a new OpenSSL library context. ```APIDOC ## LibCtx::new ### Description Creates a new OpenSSL library context. This corresponds to the OpenSSL C function `OSSL_LIB_CTX_new`. ### Method `pub fn new() -> Result` ### Parameters None. ### Returns - `Result` - A new `LibCtx` instance on success, or an `ErrorStack` on failure. ``` -------------------------------- ### rchunks example Source: https://docs.rs/openssl/latest/openssl/hash/struct.DigestBytes.html Returns an iterator over chunks of chunk_size elements starting from the end. The last chunk may be shorter if chunk_size does not divide the length. Panics if chunk_size is zero. ```rust let slice = ['l', 'o', 'r', 'e', 'm']; let mut iter = slice.rchunks(2); assert_eq!(iter.next().unwrap(), &['e', 'm']); assert_eq!(iter.next().unwrap(), &['o', 'r']); assert_eq!(iter.next().unwrap(), &['l']); assert!(iter.next().is_none()); ``` -------------------------------- ### array_windows example Source: https://docs.rs/openssl/latest/openssl/hash/struct.DigestBytes.html Returns an iterator over overlapping windows of N elements starting at the beginning. If N is greater than the slice length, no windows are returned. Panics if N is zero. ```rust let slice = [0, 1, 2, 3]; let mut iter = slice.array_windows(); assert_eq!(iter.next().unwrap(), &[0, 1]); assert_eq!(iter.next().unwrap(), &[1, 2]); assert_eq!(iter.next().unwrap(), &[2, 3]); assert!(iter.next().is_none()); ``` -------------------------------- ### PkeyCtx::sign_init Source: https://docs.rs/openssl/latest/openssl/pkey_ctx/index.html Initializes the context for signing operations. Must be called before signing data. ```APIDOC ## PkeyCtx::sign_init ### Description Initializes the context for signing operations. Must be called before signing data. ### Method Initialization ### Returns - **Result<()>** - Ok on success, or an error. ### Example ```rust use openssl::pkey_ctx::PkeyCtx; use openssl::pkey::PKey; use openssl::rsa::Rsa; let key = Rsa::generate(4096).unwrap(); let key = PKey::from_rsa(key).unwrap(); let mut ctx = PkeyCtx::new(&key).unwrap(); ctx.sign_init().unwrap(); ``` ``` -------------------------------- ### X509StoreBuilder::new Source: https://docs.rs/openssl/latest/src/openssl/x509/store.rs.html Creates a new X509StoreBuilder instance for building an X509 certificate store. ```APIDOC ## X509StoreBuilder::new ### Description Returns a builder for a certificate store. The store is initially empty. ### Method new ### Parameters None ### Returns - **Result** - A new builder instance or an error. ``` -------------------------------- ### split with separators at start/end Source: https://docs.rs/openssl/latest/openssl/string/struct.OpensslString.html Shows that separators at the start or end of a string are neighbored by empty strings. The example splits "010" on "0". ```rust let d: Vec<_> = "010".split("0").collect(); assert_eq!(d, &["", "1", ""]); ``` -------------------------------- ### Option::product example Source: https://docs.rs/openssl-sys/0.9.117/openssl_sys/type.tls_session_ticket_ext_cb_fn.html Shows how `Option::product` multiplies parsed numbers from a vector of strings. If any parse fails, the result is `None` and no further elements are taken. ```rust let nums = vec!["5", "10", "1", "2"]; let total: Option = nums.iter().map(|w| w.parse::().ok()).product(); assert_eq!(total, Some(100)); let nums = vec!["5", "10", "one", "2"]; let total: Option = nums.iter().map(|w| w.parse::().ok()).product(); assert_eq!(total, None); ``` -------------------------------- ### iter: iterate over slice items Source: https://docs.rs/openssl/latest/openssl/hash/struct.DigestBytes.html Returns an iterator over the slice, yielding all items from start to end. The example iterates over a slice of integers and asserts each yielded value, ending with `None`. ```rust let x = &[1, 2, 4]; let mut iterator = x.iter(); assert_eq!(iterator.next(), Some(&1)); assert_eq!(iterator.next(), Some(&2)); assert_eq!(iterator.next(), Some(&4)); assert_eq!(iterator.next(), None); ``` -------------------------------- ### rchunks_exact example Source: https://docs.rs/openssl/latest/openssl/hash/struct.DigestBytes.html Demonstrates the rchunks_exact method on a slice, which returns non-overlapping chunks of a fixed size starting from the end. The remainder is retrieved via the remainder() method. Panics if chunk_size is zero. ```rust let slice = ['l', 'o', 'r', 'e', 'm']; let mut iter = slice.rchunks_exact(2); assert_eq!(iter.next().unwrap(), &['e', 'm']); assert_eq!(iter.next().unwrap(), &['o', 'r']); assert!(iter.next().is_none()); assert_eq!(iter.remainder(), &['l']); ``` -------------------------------- ### PkeyCtx::keygen_init Source: https://docs.rs/openssl/latest/openssl/pkey_ctx/index.html Initializes the context for key generation. Must be called before generating a key. ```APIDOC ## PkeyCtx::keygen_init ### Description Initializes the context for key generation. Must be called before generating a key. ### Method Initialization ### Returns - **Result<()>** - Ok on success, or an error. ### Example ```rust use openssl::pkey_ctx::PkeyCtx; use openssl::pkey::Id; let mut ctx = PkeyCtx::new_id(Id::CMAC).unwrap(); ctx.keygen_init().unwrap(); ``` ``` -------------------------------- ### Example: as_ref with map Source: https://docs.rs/openssl-sys/0.9.117/openssl_sys/type.tls_session_ticket_ext_cb_fn.html Shows how to use `Option::as_ref` to convert `Option` to `Option<&String>` so that `map` can be used without moving the original value. The example prints the original `text` after the operation. ```rust let text: Option = Some("Hello, world!".to_string()); // First, cast `Option` to `Option<&String>` with `as_ref`, // then consume *that* with `map`, leaving `text` on the stack. let text_length: Option = text.as_ref().map(|s| s.len()); println!("still can print text: {text:?}"); ``` -------------------------------- ### rchunks_exact_mut example Source: https://docs.rs/openssl/latest/openssl/hash/struct.DigestBytes.html Demonstrates the rchunks_exact_mut method on a mutable slice, which returns mutable chunks of a fixed size starting from the end. The remainder is omitted and can be retrieved via into_remainder(). Panics if chunk_size is zero. ```rust let v = &mut [0, 0, 0, 0, 0]; let mut count = 1; for chunk in v.rchunks_exact_mut(2) { for elem in chunk.iter_mut() { *elem += count; } count += 1; } assert_eq!(v, &[0, 2, 2, 1, 1]); ``` -------------------------------- ### partition_point example Source: https://docs.rs/openssl/latest/openssl/hash/struct.DigestBytes.html Example for the `partition_point` method, showing how to find the index of the first element that does not satisfy the predicate. The slice is partitioned, so the predicate returns true for the first part and false for the second. ```rust let v = [1, 2, 3, 3, 5, 6, 7]; let i = v.partition_point(|&x| x < 5); ``` -------------------------------- ### rsplitn: split from end into at most n subslices Source: https://docs.rs/openssl/latest/openssl/hash/struct.DigestBytes.html Use to split a slice into at most n subslices starting from the end and working backwards. The matched element is excluded. The example prints the groups [50] and [10, 40, 30, 20]. ```rust let v = [10, 40, 30, 20, 60, 50]; for group in v.rsplitn(2, |num| *num % 3 == 0) { println!("{group:?}"); } ``` -------------------------------- ### Option sum examples Source: https://docs.rs/openssl-sys/0.9.117/openssl_sys/type.tls_session_ticket_ext_cb_fn.html Two examples showing how the sum of Option values behaves. The first sums over an existing vector of words and yields Some(5); the second defines the vector and yields None because no matching character is found. ```rust let total: Option = words.iter().map(|w| w.find('a')).sum(); assert_eq!(total, Some(5)); ``` ```rust let words = vec!["have", "a", "good", "day"]; let total: Option = words.iter().map(|w| w.find('a')).sum(); assert_eq!(total, None); ``` -------------------------------- ### rsplitn_mut: mutable split from end into at most n subslices Source: https://docs.rs/openssl/latest/openssl/hash/struct.DigestBytes.html Use to split a mutable slice into at most n mutable subslices starting from the end. The matched element is excluded. The example modifies the first element of each group and asserts the resulting slice. ```rust let mut s = [10, 40, 30, 20, 60, 50]; for group in s.rsplitn_mut(2, |num| *num % 3 == 0) { group[0] = 1; } assert_eq!(s, [1, 40, 30, 20, 60, 1]); ``` -------------------------------- ### Install OpenSSL for automatic detection on Unix-like systems Source: https://docs.rs/openssl Install OpenSSL development packages on various Unix-like systems so that `openssl-sys` can automatically detect the installation via `pkg-config` (or Homebrew/vcpkg on macOS/Windows). Each command installs the required headers and libraries for the given package manager. ```bash # macOS (Homebrew) $ brew install openssl@4 # macOS (MacPorts) $ sudo port install openssl # macOS (pkgsrc) $ sudo pkgin install openssl # Arch Linux $ sudo pacman -S pkgconf openssl # Debian and Ubuntu $ sudo apt-get install pkg-config libssl-dev # Fedora $ sudo dnf install pkgconf perl-FindBin perl-IPC-Cmd openssl-devel # Alpine Linux $ apk add pkgconf openssl-dev # openSUSE $ sudo zypper in libopenssl-devel ``` -------------------------------- ### PkeyCtx::verify_init Source: https://docs.rs/openssl/latest/openssl/pkey_ctx/index.html Initializes the context for verification operations. Must be called before verifying a signature. ```APIDOC ## PkeyCtx::verify_init ### Description Initializes the context for verification operations. Must be called before verifying a signature. ### Method Initialization ### Returns - **Result<()>** - Ok on success, or an error. ### Example ```rust use openssl::pkey_ctx::PkeyCtx; use openssl::pkey::PKey; use openssl::rsa::Rsa; let key = Rsa::generate(4096).unwrap(); let key = PKey::from_rsa(key).unwrap(); let mut ctx = PkeyCtx::new(&key).unwrap(); ctx.verify_init().unwrap(); ``` ``` -------------------------------- ### open_init Source: https://docs.rs/openssl/latest/openssl/cipher_ctx/struct.CipherCtxRef.html Initializes the context for envelope decryption. Corresponds to EVP_OpenInit. ```APIDOC ## open_init ### Description Initializes the context to perform envelope decryption. Normally called once with all arguments present. The process may be split by first providing the cipher alone and then providing the rest of the arguments in a second call. ### Method `pub fn open_init(&mut self, type_: Option<&CipherRef>, encrypted_key: &[u8], iv: Option<&[u8]>, priv_key: Option<&PKeyRef>) -> Result<(), ErrorStack> where T: HasPrivate` ### Parameters - `type_` (`Option<&CipherRef>`) - Optional - The cipher to use. If `None`, the other arguments must be provided after a previous cipher initialization. - `encrypted_key` (`&[u8]`) - Required - The encrypted symmetric key. - `iv` (`Option<&[u8]>`) - Optional - The initialization vector. Must be at least the cipher's IV size. - `priv_key` (`Option<&PKeyRef>`) - Optional - The private key used to decrypt the symmetric key. ### Panics - Panics if the IV buffer is smaller than the cipher's required IV size. - Panics if the IV is provided before the cipher. ### Returns - `Result<(), ErrorStack>` - Ok on success, or an error stack on failure. ### Corresponding OpenSSL Function `EVP_OpenInit` ``` -------------------------------- ### Option::is_none Example Source: https://docs.rs/openssl-sys/0.9.117/openssl_sys/type.tls_session_secret_cb_fn.html Example for the `is_none` method, which returns `true` if the option is a `None` value. ```rust let x: Option = Some(2); assert_eq!(x.is_none(), false); let x: Option = None; assert_eq!(x.is_none(), true); ``` -------------------------------- ### Create a new Conf parser with ConfMethod::default() Source: https://docs.rs/openssl/latest/src/openssl/conf.rs.html Shows how to create a new `Conf` parser using the default OpenSSL configuration method. Requires the `openssl::conf` module and the `ConfMethod::default()` method. ```rust use openssl::conf::{Conf, ConfMethod}; let conf = Conf::new(ConfMethod::default()); ``` -------------------------------- ### pub fn split_at(&self, mid: usize) -> (&str, &str) Source: https://docs.rs/openssl/latest/openssl/string/struct.OpensslStringRef.html Divides one string slice into two at a byte offset. The argument, `mid`, should be a byte offset from the start of the string. It must also be on the boundary of a UTF-8 code point. The first returned slice contains exactly the first `mid` bytes, and the second contains all remaining bytes. To get mutable string slices instead, see the `split_at_mut` method. ```APIDOC ## pub fn split_at(&self, mid: usize) -> (&str, &str) ### Description Divides one string slice into two at a byte offset. The argument, `mid`, should be a byte offset from the start of the string. It must also be on the boundary of a UTF-8 code point. The first returned slice contains exactly the first `mid` bytes, and the second contains all remaining bytes. To get mutable string slices instead, see the `split_at_mut` method. ### Method split_at ### Signature pub fn split_at(&self, mid: usize) -> (&str, &str) ### Parameters - **mid** (usize) - Required - The byte offset at which to split the string. ### Panics Panics if `mid` is not on a UTF-8 code point boundary, or if it is past the end of the last code point of the string slice. For a non-panicking alternative see `split_at_checked`. ### Examples ```rust let s = "Per Martin-Löf"; let (first, last) = s.split_at(3); assert_eq!("Per", first); assert_eq!(" Martin-Löf", last); ``` ``` -------------------------------- ### Example: into_flat_iter with feature gate Source: https://docs.rs/openssl-sys/0.9.117/openssl_sys/type.tls_session_ticket_ext_cb_fn.html Demonstrates the nightly-only experimental API `option_into_flat_iter`. Requires the `#![feature(option_into_flat_iter)]` attribute. Shows that `Some` values are flattened into an iterator and `None` produces an empty iterator. ```rust #![feature(option_into_flat_iter)] let o1 = Some([1, 2]); let o2 = None::<&[usize]>; assert_eq!(o1.into_flat_iter().collect::>(), [1, 2]); assert_eq!(o2.into_flat_iter().collect::>(), Vec::<&usize>::new()); ``` -------------------------------- ### is_empty() example Source: https://docs.rs/openssl/latest/openssl/string/struct.OpensslString.html Example for the `is_empty` method from `Deref`. Checks if the string has zero bytes. ```rust let s = ""; assert!(s.is_empty()); let s = "not empty"; assert!(!s.is_empty()); ``` -------------------------------- ### Option::is_some_and Example Source: https://docs.rs/openssl-sys/0.9.117/openssl_sys/type.tls_session_secret_cb_fn.html Example for the `is_some_and` method, which returns `true` if the option is `Some` and the value matches a predicate. ```rust let x: Option = Some(2); assert_eq!(x.is_some_and(|x| x > 1), true); let x: Option = Some(0); assert_eq!(x.is_some_and(|x| x > 1), false); let x: Option = None; assert_eq!(x.is_some_and(|x| x > 1), false); let x: Option = Some("ownership".to_string()); assert_eq!(x.as_ref().is_some_and(|x| x.len() > 1), true); println!("still alive {:?}", x); ``` -------------------------------- ### Create Conf with Conf::new Source: https://docs.rs/openssl/latest/openssl/conf/struct.Conf.html Creates a configuration parser using the default method. Corresponds to NCONF_new. ```rust use openssl::conf::{Conf, ConfMethod}; let conf = Conf::new(ConfMethod::default()); ``` -------------------------------- ### X509_STORE_new Source: https://docs.rs/openssl-sys/0.9.117/src/openssl_sys/handwritten/x509_vfy.rs.html Creates a new X509_STORE structure. ```APIDOC ## X509_STORE_new ### Description Creates a new X509_STORE structure. ### Method FFI Function ### Signature ```rust pub fn X509_STORE_new() -> *mut X509_STORE; ``` ### Parameters None ### Return Value - **X509_STORE** - Pointer to the newly created store, or NULL on failure. ```