### Initialize YubiHSM 2 with Profile Source: https://docs.rs/yubihsm/latest/src/yubihsm/setup.rs.html Initializes an HSM device with a given profile without erasing it first. Assumes the HSM is in a clean state. This function installs a temporary setup authentication key, then uses it to provision the device according to the profile. ```rust pub fn init_with_profile(client: Client, profile: Profile) -> Result { let setup_auth_key_id = profile .setup_auth_key_id .ok_or_else(|| format_err!(ErrorKind::SetupFailed, "profile setup_auth_key_id unset!"))?; let temp_auth_key = authentication::Key::random(); client .put_authentication_key( setup_auth_key_id, SETUP_KEY_LABEL.into(), Domain::all(), Capability::all(), Capability::all(), authentication::Algorithm::YubicoAes, temp_auth_key.clone(), ) .map_err(|e| { format_err!( ErrorKind::SetupFailed, "error putting authentication key: {}", e ) })?; info!( "installed temporary setup authentication key into slot {}", setup_auth_key_id ); let connector = client.connector().clone(); // Create a new client, connecting with the temporary auth key let client = Client::open( connector, Credentials::new(setup_auth_key_id, temp_auth_key), false, ) .map_err(|e| { format_err!( ErrorKind::SetupFailed, "error reconnecting to HSM with setup auth key: {}", e ) })?; warn!( "deleting default authentication key from slot {}", DEFAULT_AUTHENTICATION_KEY_ID ); client .delete_object( DEFAULT_AUTHENTICATION_KEY_ID, object::Type::AuthenticationKey, ) .map_err(|e| { format_err!( ErrorKind::SetupFailed, "error deleting default authentication key from slot {}: {}", DEFAULT_AUTHENTICATION_KEY_ID, e ) })?; let report = profile.provision(&client)?; if profile.delete_setup_auth_key { warn!( "deleting temporary setup authentication key from slot {}", setup_auth_key_id ); client .delete_object(setup_auth_key_id, object::Type::AuthenticationKey) .map_err(|e| { format_err!( ErrorKind::SetupFailed, "error deleting temporary setup authentication key from slot {}: {}", setup_auth_key_id, e ) })?; } Ok(report) } ``` -------------------------------- ### Profile::setup_auth_key_id Source: https://docs.rs/yubihsm/latest/yubihsm/setup/struct.Profile.html Configures the authentication key ID for device setup. ```APIDOC ## pub fn setup_auth_key_id(self, key_id: Option) -> Self Configure the auth key ID to use when performing device setup ``` -------------------------------- ### Configure Authentication Key ID for Setup Source: https://docs.rs/yubihsm/latest/yubihsm/setup/struct.Profile.html Set the authentication key ID to be used during the device setup process. This method returns the modified Profile instance for chaining. ```rust pub fn setup_auth_key_id(self, key_id: Option) -> Self ``` -------------------------------- ### init_with_profile Source: https://docs.rs/yubihsm/latest/yubihsm/setup/index.html Initialize an HSM device with the given profile. This function is available when the `setup` feature is enabled. ```APIDOC ## init_with_profile ### Description Initialize an HSM device with the given profile. ### Function Signature `pub fn init_with_profile(profile: Profile) -> Result` ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example None ### Response #### Success Response (Result) - `Ok(Report)`: On successful initialization, returns a `Report` containing provisioning details. #### Response Example None ### Error Handling - `Err(Error)`: Returns a `SetupError` if the initialization fails. ``` -------------------------------- ### init_with_profile Source: https://docs.rs/yubihsm/latest/yubihsm/setup/fn.init_with_profile.html Initializes an HSM device with the provided client and profile. This function is available only when the `setup` feature flag is enabled. ```APIDOC ## Function init_with_profile ### Description Initializes an HSM device with the given profile. This approach does not erase the device first, but generally assumes the HSM is in a clean state. The recommended approach is to use `erase_device_and_init_with_profile`. ### Signature ```rust pub fn init_with_profile( client: Client, profile: Profile, ) -> Result ``` ### Parameters - **client**: `Client` - The client object used to interact with the HSM. - **profile**: `Profile` - The profile to initialize the HSM with. ### Returns - `Result` - Returns a `Report` on success or an `Error` on failure. ``` -------------------------------- ### Default Profile Initialization Source: https://docs.rs/yubihsm/latest/src/yubihsm/setup/profile.rs.html Provides a default `Profile` configuration. This is useful as a starting point for custom provisioning. ```rust impl Default for Profile { fn default() -> Self { Profile { setup_auth_key_id: Some(DEFAULT_SETUP_KEY_ID), delete_setup_auth_key: true, audit_option: AuditOption::Off, roles: Vec::new(), wrap_keys: Vec::new(), report_object_id: Some(DEFAULT_REPORT_OBJECT_ID), reset_device_timeout: Duration::from_secs(10), } } } ``` -------------------------------- ### Default UsbConnection Source: https://docs.rs/yubihsm/latest/src/yubihsm/connector/usb/connection.rs.html Provides a default `UsbConnection` by opening a device with default settings. This is a convenience method for quick setup. ```rust fn default() -> Self { Devices::open(None, UsbTimeout::default()).unwrap() } ``` -------------------------------- ### erase_device_and_init_with_profile Source: https://docs.rs/yubihsm/latest/yubihsm/setup/fn.erase_device_and_init_with_profile.html Erase and reset an HSM device, then reinitialize it with the given profile. Available on crate feature `setup` only. ```APIDOC ## Function erase_device_and_init_with_profile ### Description Erase and reset an HSM device, then reinitialize it with the given profile. ### Signature ```rust pub fn erase_device_and_init_with_profile( connector: Connector, credentials: Credentials, profile: Profile, ) -> Result ``` ### Parameters * `connector`: Connector - The connection to the YubiHSM device. * `credentials`: Credentials - The credentials to use for authentication. * `profile`: Profile - The profile to initialize the device with. ### Returns * `Result` - A `Report` on success, or an `Error` on failure. ``` -------------------------------- ### Report::new Source: https://docs.rs/yubihsm/latest/yubihsm/setup/report/struct.Report.html Creates a new `yubihsm::setup::Report` instance by capturing the ambient environment state. It requires the device's serial number as input. ```APIDOC ## `new` ### Description Make a new `yubihsm::setup::Report` from the ambient environment state. ### Signature ```rust pub fn new(serial_number: SerialNumber) -> Self ``` ### Parameters * `serial_number`: `SerialNumber` - The serial number of the YubiHSM device. ``` -------------------------------- ### Get Opaque Command Structure Source: https://docs.rs/yubihsm/latest/src/yubihsm/opaque/commands/get.rs.html Defines the request and response structures for the Get Opaque command. Use this when interacting with opaque objects on the YubiHSM. ```rust use crate::{ command::{self, Command}, object, response::Response, }; use serde::{Deserialize, Serialize}; /// Request parameters for `command::get_opaque` #[derive(Serialize, Deserialize, Debug)] pub(crate) struct GetOpaqueCommand { /// Object ID of the key to obtain the corresponding opaque for pub object_id: object::Id, } impl Command for GetOpaqueCommand { type ResponseType = GetOpaqueResponse; } /// Response from `command::get_opaque` #[derive(Serialize, Deserialize, Debug)] pub(crate) struct GetOpaqueResponse(pub(crate) Vec); impl Response for GetOpaqueResponse { const COMMAND_CODE: command::Code = command::Code::GetOpaqueObject; } ``` -------------------------------- ### Create New Report Source: https://docs.rs/yubihsm/latest/yubihsm/setup/report/struct.Report.html Creates a new `yubihsm::setup::Report` instance using the ambient environment state. Requires the device's serial number. ```rust pub fn new(serial_number: SerialNumber) -> Self ``` -------------------------------- ### Handle GET /connector/status Request Source: https://docs.rs/yubihsm/latest/src/yubihsm/connector/http/server.rs.html Responds to GET requests on the `/connector/status` endpoint. It returns a simple status message along with details about the server and the YubiHSM2 connector. ```rust fn status(&self) -> Result>>, Error> { info!( "yubihsm::http-server[{}:{}]: GET /connector/status", &self.addr, self.port ); let status = [ ("status", "OK"), ("serial", "*"), ("version", env!("CARGO_PKG_VERSION")), ("pid", &process::id().to_string()), ("address", &self.addr), ("port", &self.port.to_string()), ]; let body = status .iter() .map(|(k, v)| [*k, *v].join("\n")) .collect::>() .join("\n"); Ok(http::Response::from_string(body)) } ``` -------------------------------- ### Create a New Role Object Source: https://docs.rs/yubihsm/latest/yubihsm/setup/struct.Role.html Instantiates a new Role object. This is the starting point for configuring a role before it is created on the device. ```rust pub fn new(credentials: Credentials) -> Self ``` -------------------------------- ### Manually Create Box from Scratch Source: https://docs.rs/yubihsm/latest/yubihsm/error/type.BoxError.html This example demonstrates how to manually allocate memory using the global allocator and construct a Box from it. Ensure the memory layout matches Box's requirements and initialize the memory before creating the Box. ```rust #![feature(box_vec_non_null)] use std::alloc::{alloc, Layout}; use std::ptr::NonNull; unsafe { let non_null = NonNull::new(alloc(Layout::new::()).cast::()) .expect("allocation failed"); // In general .write is required to avoid attempting to destruct // the (uninitialized) previous contents of `non_null`. non_null.write(5); let x = Box::from_non_null(non_null); } ``` -------------------------------- ### Get Storage Info Response Structure Source: https://docs.rs/yubihsm/latest/src/yubihsm/device/storage.rs.html The `Info` struct represents the response from the Get Storage Info command, providing details about the device's storage capacity and utilization. ```APIDOC ## Get Storage Info Response ### Description This structure contains information about the YubiHSM device's storage. ### Fields - **total_records** (u16) - Total number of storage records available on the device. - **free_records** (u16) - The number of storage records that are currently free and available for use. - **total_pages** (u16) - Total number of storage pages on the device. - **free_pages** (u16) - The number of storage pages that are currently free. - **page_size** (u16) - The size of each storage page in bytes. ### Response Example ```json { "total_records": 1024, "free_records": 512, "total_pages": 256, "free_pages": 128, "page_size": 4096 } ``` ``` -------------------------------- ### Version Struct Source: https://docs.rs/yubihsm/latest/yubihsm/setup/report/struct.Version.html The Version struct is used to represent version information. It is available only when the `setup` feature is enabled. ```APIDOC ## Struct Version Available on **crate feature `setup`** only. ```rust pub struct Version(/* private fields */); ``` ### Description Report versions. ``` -------------------------------- ### YubiHSM Setup Error Definitions Source: https://docs.rs/yubihsm/latest/src/yubihsm/setup/error.rs.html Defines the `ErrorKind` enum for setup-related errors and provides a `context` method for creating error contexts. This is useful for encapsulating specific setup failures. ```rust use crate::error::{BoxError, Context}; use thiserror::Error; /// Setup-related errors pub type Error = crate::Error; /// Kinds of setup-related errors #[derive(Copy, Clone, Debug, Eq, Error, PartialEq)] pub enum ErrorKind { /// Invalid label #[error("invalid label")] LabelInvalid, /// Errors involving setup report generation #[error("report failed")] ReportFailed, /// Error performing setup #[error("setup failed")] SetupFailed, } impl ErrorKind { /// Create an error context from this error pub fn context(self, source: impl Into) -> Context { Context::new(self, Some(source.into())) } } ``` -------------------------------- ### init_with_profile Source: https://docs.rs/yubihsm/latest/src/yubihsm/setup.rs.html Initializes a YubiHSM 2 device with a given profile without erasing it first. Assumes the device is in a clean state. Use `erase_device_and_init_with_profile` for a guaranteed clean setup. ```APIDOC ## init_with_profile ### Description Initialize an HSM device with the given profile. This approach does not erase the device first, but generally assumes the HSM is in a clean state. The recommended approach is to use `erase_device_and_init_with_profile`. ### Function Signature pub fn init_with_profile(client: Client, profile: Profile) -> Result ### Parameters - `client` (Client): An authenticated client connected to the YubiHSM device. - `profile` (Profile): The device profile to apply during initialization. ### Returns - `Result`: A `Report` containing information about the initialization process, or an `Error` if the process fails. ``` -------------------------------- ### Get Pseudo Random Bytes Command Structure Source: https://docs.rs/yubihsm/latest/src/yubihsm/device/commands/rng.rs.html Defines the request and response structures for the Get Pseudo Random Bytes command. Use this to generate requests for random bytes from the YubiHSM. ```rust use crate::{ command::{self, Command, MAX_MSG_SIZE}, response::Response, }; use serde::{Deserialize, Serialize}; /// Max message size - tag byte - 16-bit response length field pub(crate) const MAX_RAND_BYTES: usize = MAX_MSG_SIZE - 1 - 2; /// Request parameters for `command::get_pseudo_random` #[derive(Serialize, Deserialize, Debug)] pub(crate) struct GetPseudoRandomCommand { /// Number of random bytes to return pub bytes: u16, } impl Command for GetPseudoRandomCommand { type ResponseType = GetPseudoRandomResponse; } /// Response from `command::get_pseudo_random` #[derive(Serialize, Deserialize, Debug)] pub(crate) struct GetPseudoRandomResponse { /// Bytes of pseudo random data returned from the YubiHSM pub bytes: Vec, } impl Response for GetPseudoRandomResponse { const COMMAND_CODE: command::Code = command::Code::GetPseudoRandom; } ``` -------------------------------- ### coordinates Source: https://docs.rs/yubihsm/latest/yubihsm/ecdsa/sec1/type.EncodedPoint.html Gets the `Coordinates` for this `EncodedPoint`. ```APIDOC ### pub fn coordinates(&self) -> Coordinates<'_, Size> Get the `Coordinates` for this `EncodedPoint`. ``` -------------------------------- ### Create YubiHSM Provisioning Report Source: https://docs.rs/yubihsm/latest/src/yubihsm/setup/report.rs.html Constructs a new `Report` using ambient environment variables for hostname and username, and the current UTC time. It requires a device serial number and formats the software string using package name and version. ```rust pub fn new(serial_number: SerialNumber) -> Self { // TODO: handle these better on operating systems other than *IX Report { version: Version(1), uuid: uuid::new_v4(), device_serial_number: serial_number.to_string(), username: env::var("LOGNAME").ok(), hostname: env::var("HOSTNAME").ok(), date: DateTime::now_utc(), software: format!("{} {}", env!("CARGO_PKG_NAME"), env!("CARGO_PKG_VERSION")), } } ``` -------------------------------- ### Key Generation and Configuration Source: https://docs.rs/yubihsm/latest/src/yubihsm/wrap/key.rs.html Demonstrates how to generate a random wrap key and configure its properties like label, domains, and capabilities. ```APIDOC ## Key Generation and Configuration ### Description This section covers the creation and configuration of `wrap::Key` instances. ### Methods #### `Key::generate_random(key_id: object::Id, algorithm: wrap::Algorithm) -> Self` Generates a new random wrap key with the specified algorithm and key ID. #### `Key::from_bytes(key_id: object::Id, bytes: &[u8]) -> Result` Creates a `wrap::Key` from provided byte slice. The byte slice must be 16, 24, or 32 bytes long. ### Builder Methods #### `label(mut self, label: object::Label) -> Self` Sets the object label for the wrap key. #### `domains(mut self, domains: Domain) -> Self` Sets the domains in which this wrap key can be used. #### `capabilities(mut self, capabilities: Capability) -> Self` Sets the capabilities of the wrap key itself. #### `delegated_capabilities(mut self, capabilities: Capability) -> Self` Sets the capabilities that this wrap key can delegate to imported objects. ``` -------------------------------- ### Convert Client Error to Setup Error Source: https://docs.rs/yubihsm/latest/src/yubihsm/setup/error.rs.html Implements the `From` trait to convert `crate::client::Error` into the library's setup error type. This simplifies error handling by allowing direct conversion of underlying client errors. ```rust impl From for Error { fn from(client_error: crate::client::Error) -> Error { ErrorKind::SetupFailed.context(client_error).into() } } ``` -------------------------------- ### oid Source: https://docs.rs/yubihsm/latest/yubihsm/ecdsa/struct.Signature.html Get the OID associated with this value. ```APIDOC ## oid ### Description Get the OID associated with this value. ### Returns - `ObjectIdentifier` - The object identifier. ``` -------------------------------- ### tag Source: https://docs.rs/yubihsm/latest/yubihsm/ecdsa/sec1/type.EncodedPoint.html Gets the SEC1 tag for this `EncodedPoint`. ```APIDOC ### pub fn tag(&self) -> Tag Get the SEC1 tag for this `EncodedPoint` ``` -------------------------------- ### Provision YubiHSM 2 with a Profile Source: https://docs.rs/yubihsm/latest/yubihsm/setup/struct.Profile.html Apply the configured Profile to provision the YubiHSM 2 device using the provided `Client`. Returns a `Report` on success or an `Error` on failure. ```rust pub fn provision(&self, client: &Client) -> Result ``` -------------------------------- ### erase_device_and_init_with_profile Source: https://docs.rs/yubihsm/latest/yubihsm/setup/index.html Erase and reset an HSM device, then reinitialize it with the given profile. This function is available when the `setup` feature is enabled. ```APIDOC ## erase_device_and_init_with_profile ### Description Erase and reset an HSM device, then reinitialize it with the given profile. ### Function Signature `pub fn erase_device_and_init_with_profile(profile: Profile) -> Result` ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example None ### Response #### Success Response (Result) - `Ok(Report)`: On successful initialization, returns a `Report` containing provisioning details. #### Response Example None ### Error Handling - `Err(Error)`: Returns a `SetupError` if the initialization fails. ``` -------------------------------- ### Create and Initialize an Uninitialized Box Source: https://docs.rs/yubihsm/latest/yubihsm/error/type.BoxError.html Shows how to create a Box with uninitialized contents and then safely initialize it. This requires `unsafe` to assume initialization. ```rust let mut five = Box::::new_uninit(); // Deferred initialization: five.write(5); let five = unsafe { five.assume_init() }; assert_eq!(*five, 5) ``` -------------------------------- ### len Source: https://docs.rs/yubihsm/latest/yubihsm/ecdsa/sec1/type.EncodedPoint.html Gets the length of the encoded point in bytes. ```APIDOC ### pub fn len(&self) -> usize Get the length of the encoded point in bytes ``` -------------------------------- ### Get Template Algorithm Source: https://docs.rs/yubihsm/latest/yubihsm/template/enum.Template.html Retrieves the algorithm associated with the template. ```rust pub fn algorithm(&self) -> Algorithm ``` -------------------------------- ### PublicKey Ownership and Cloning Source: https://docs.rs/yubihsm/latest/yubihsm/ed25519/struct.PublicKey.html Demonstrates how to obtain owned data from borrowed data and how to clone data into an existing mutable target. ```APIDOC ## fn to_owned(&self) -> T Creates owned data from borrowed data, usually by cloning. ## fn clone_into(&self, target: &mut T) Uses borrowed data to replace owned data, usually by cloning. ``` -------------------------------- ### Erase and Initialize YubiHSM 2 with Profile Source: https://docs.rs/yubihsm/latest/src/yubihsm/setup.rs.html Resets the HSM device and initializes it with the specified profile. This is the recommended approach for a clean setup. ```rust pub fn erase_device_and_init_with_profile( connector: Connector, credentials: Credentials, profile: Profile, ) -> Result { // Reset the device let mut client = Client::open(connector, credentials, false)?; client.reset_device_and_reconnect(profile.reset_device_timeout)?; init_with_profile(client, profile) } ``` -------------------------------- ### as_bytes Source: https://docs.rs/yubihsm/latest/yubihsm/ecdsa/sec1/type.EncodedPoint.html Gets a byte slice containing the serialized `EncodedPoint`. ```APIDOC ### pub fn as_bytes(&self) -> &[u8] Get byte slice containing the serialized `EncodedPoint`. ``` -------------------------------- ### Profile Configuration Methods Source: https://docs.rs/yubihsm/latest/src/yubihsm/setup/profile.rs.html Methods for creating and customizing a `Profile`. These allow setting specific parameters like auth key ID, audit options, roles, and wrap keys. ```rust impl Profile { /// Create a new empty profile pub fn new() -> Self { Self::default() } /// Configure the auth key ID to use when performing device setup pub fn setup_auth_key_id(mut self, key_id: Option) -> Self { self.setup_auth_key_id = key_id; self } /// Enable mandatory consumption of the audit log. See: /// /// pub fn audit_option(mut self, value: AuditOption) -> Self { self.audit_option = value; self } /// Set the initial roles to provision pub fn roles(mut self, roles: I) -> Self where I: IntoIterator, { self.roles = roles.into_iter().collect(); self } /// Set the wrap keys to initially provision pub fn wrap_keys(mut self, keys: I) -> Self where I: IntoIterator, { self.wrap_keys = keys.into_iter().collect(); self } /// Use this profile to provision the YubiHSM 2 with the given client pub fn provision(&self, client: &Client) -> Result { for role in &self.roles { info!("installing role: {}", role.authentication_key_label); role.create(client)?; } for wrap_key in &self.wrap_keys { info!("installing wrap key: {}", &wrap_key.import_params.label); wrap_key.create(client)?; } if self.audit_option != AuditOption::Off { info!("setting force audit to: {:?}", self.audit_option); client.set_force_audit_option(self.audit_option)?; } let report = Report::new(client.device_info()?.serial_number); if let Some(report_object_id) = self.report_object_id { info!( "storing provisioning report in opaque object 0x{:x}", report_object_id ); report.store(client, report_object_id)?; } Ok(report) } } ``` -------------------------------- ### Default and Initialization Source: https://docs.rs/yubihsm/latest/yubihsm/capability/struct.Capability.html Methods for creating default and initialized Capability values. ```APIDOC ## Default and Initialization ### `default() -> Self` Returns the default value for a Capability. ### `from_bits_retain(bits: u64) -> Capability` Converts from a bits value exactly. ### `from_bits(bits: Self::Bits) -> Option` Converts from a bits value. Returns `None` if the bits are invalid. ### `from_bits_truncate(bits: Self::Bits) -> Self` Converts from a bits value, unsetting any unknown bits. ### `from_name(name: &str) -> Option` Gets a capability value with the bits of a flag with the given name set. ### `empty() -> Self` Gets a capability value with all bits unset. ### `all() -> Self` Gets a capability value with all known bits set. ``` -------------------------------- ### Get Coordinates Source: https://docs.rs/yubihsm/latest/yubihsm/ecdsa/sec1/type.EncodedPoint.html Provides access to the Coordinates struct for this EncodedPoint. ```rust pub fn coordinates(&self) -> Coordinates<'_, Size> ``` -------------------------------- ### Initialize MockHsm State Source: https://docs.rs/yubihsm/latest/src/yubihsm/mockhsm/state.rs.html Creates a new instance of the server's mutable interior state for the MockHsm. This is the default starting state. ```rust pub fn new() -> Self { Self { command_audit_options: CommandAuditOptions::default(), force_audit: AuditOption::Off, sessions: BTreeMap::new(), objects: Objects::default(), } } ``` -------------------------------- ### Get S Component as NonZeroScalar Source: https://docs.rs/yubihsm/latest/yubihsm/ecdsa/nistp256/type.Signature.html Retrieves the `s` component of the signature as a `NonZeroScalar`. ```rust pub fn s(&self) -> NonZeroScalar ``` -------------------------------- ### Get Device Info Source: https://docs.rs/yubihsm/latest/src/yubihsm/client.rs.html Retrieves information about the YubiHSM device. ```APIDOC ## device_info ### Description Gets information about the HSM device. ### Method `pub fn device_info(&self) -> Result` ### Response #### Success Response - `Ok(device::Info)`: An object containing the device information. #### Error Response - `Err(Error)`: If retrieving device information fails. ``` -------------------------------- ### Connection::open Source: https://docs.rs/yubihsm/latest/src/yubihsm/connector/http/client/connection.rs.html Establishes a new TCP connection to an HTTP server with specified options. ```APIDOC ## Connection::open ### Description Creates a new connection to an HTTP server at the specified address and port, using the provided connection options. ### Signature ```rust pub fn open(addr: &str, port: u16, opts: &ConnectionOptions) -> Result ``` ### Parameters * `addr` (string) - The hostname or IP address of the HTTP server. * `port` (u16) - The port number of the HTTP server. * `opts` (`&ConnectionOptions`) - Options for configuring the connection, such as timeout. ### Returns * `Result` - Returns a `Connection` instance on success or an `Error` on failure. ``` -------------------------------- ### Create New HTTP Server Instance Source: https://docs.rs/yubihsm/latest/src/yubihsm/connector/http/server.rs.html Initializes a new HTTP server instance bound to the specified address and port, ready to handle requests for the YubiHSM2 connector. Requires `HttpConfig` for address/port and a `Connector` instance. ```rust pub fn new(config: &HttpConfig, connector: Connector) -> Result { let server = http::Server::http(format!( ":{}", &config.addr, config.port)) .map_err(|e| format_err!(AddrInvalid, "couldn't create HTTP server: {}", e))?; info!( "yubihsm::http-server[{}:{}]: listening for connections", &config.addr, config.port ); Ok(Self { addr: config.addr.clone(), port: config.port, server, connector, }) } ``` -------------------------------- ### Get Object Source: https://docs.rs/yubihsm/latest/src/yubihsm/mockhsm/object/objects.rs.html Retrieves an object from the MockHsm by its ID and type. ```APIDOC ## get ### Description Gets an object from the MockHsm. ### Method `Objects::get` ### Parameters - `object_id` (Id) - The unique identifier of the object to retrieve. - `object_type` (Type) - The type of the object to retrieve. ### Returns An `Option<&Object>` containing a reference to the object if found, otherwise `None`. ``` -------------------------------- ### Creating a Wrap Key in the HSM Source: https://docs.rs/yubihsm/latest/src/yubihsm/wrap/key.rs.html Shows how to use a configured `wrap::Key` object to create the corresponding key within the YubiHSM device. ```APIDOC ## Create Wrap Key ### Description This operation creates the wrap key within the YubiHSM device using the configured parameters. ### Method `Key::create(&self, client: &Client) -> Result<(), client::Error>` ### Parameters - `client` (*Client*): A reference to an authenticated YubiHSM client. ### Response #### Success Response (200) - `()`: Indicates the key was successfully created. #### Error Response - `client::Error`: If there was an issue communicating with the HSM or creating the key. ``` -------------------------------- ### to_bytes Source: https://docs.rs/yubihsm/latest/yubihsm/ecdsa/sec1/type.EncodedPoint.html Gets a boxed byte slice containing the serialized `EncodedPoint`. ```APIDOC ### pub fn to_bytes(&self) -> Box<[u8]> Get boxed byte slice containing the serialized `EncodedPoint` ``` -------------------------------- ### Run the server's main loop Source: https://docs.rs/yubihsm/latest/yubihsm/connector/http/struct.Server.html Starts the server's main loop, which is responsible for processing incoming requests. This method returns a Result indicating success or failure. ```rust pub fn run(&self) -> Result<(), Error> ``` -------------------------------- ### Get Opaque Source: https://docs.rs/yubihsm/latest/src/yubihsm/client.rs.html Retrieves an opaque object stored in the HSM by its ID. ```APIDOC ## get_opaque ### Description Get an opaque object stored in the HSM. ### Method Signature ```rust pub fn get_opaque(&self, object_id: object::Id) -> Result, Error> ``` ### Parameters - **object_id** (object::Id) - The ID of the opaque object to retrieve. ### Returns - **Vec** - The opaque object data as a byte vector. ``` -------------------------------- ### Create a new HTTP server Source: https://docs.rs/yubihsm/latest/yubihsm/connector/http/struct.Server.html Initializes a new HTTP service that provides access to the YubiHSM2. Requires an HttpConfig and a Connector instance. ```rust pub fn new(config: &HttpConfig, connector: Connector) -> Result ``` -------------------------------- ### y Source: https://docs.rs/yubihsm/latest/yubihsm/ecdsa/sec1/type.EncodedPoint.html Gets the y-coordinate for this `EncodedPoint`. Returns `None` if this point is compressed or the identity point. ```APIDOC ### pub fn y(&self) -> Option<&GenericArray> Get the y-coordinate for this `EncodedPoint`. Returns `None` if this point is compressed or the identity point. ``` -------------------------------- ### Manually Create a Box from Global Allocator Source: https://docs.rs/yubihsm/latest/yubihsm/error/type.BoxError.html This example shows how to manually allocate memory using the global allocator and then create a Box from that raw pointer. This is an unsafe operation and requires careful management of memory. ```rust use std::alloc::{alloc, Layout}; unsafe { let ptr = alloc(Layout::new::()) as *mut i32; // In general .write is required to avoid attempting to destruct // the (uninitialized) previous contents of `ptr`, though for this // simple example `*ptr = 5` would have worked as well. ptr.write(5); let x = Box::from_raw(ptr); } ``` -------------------------------- ### Create a New Empty Profile Source: https://docs.rs/yubihsm/latest/yubihsm/setup/struct.Profile.html Instantiate a new, empty Profile to begin configuring provisioning settings. ```rust pub fn new() -> Self ``` -------------------------------- ### x Source: https://docs.rs/yubihsm/latest/yubihsm/ecdsa/sec1/type.EncodedPoint.html Gets the x-coordinate for this `EncodedPoint`. Returns `None` if this point is the identity point. ```APIDOC ### pub fn x(&self) -> Option<&GenericArray> Get the x-coordinate for this `EncodedPoint`. Returns `None` if this point is the identity point. ``` -------------------------------- ### Get R Component as NonZeroScalar Source: https://docs.rs/yubihsm/latest/yubihsm/ecdsa/nistp256/type.Signature.html Retrieves the `r` component of the signature as a `NonZeroScalar`. ```rust pub fn r(&self) -> NonZeroScalar ``` -------------------------------- ### Create a Boxed Integer Source: https://docs.rs/yubihsm/latest/yubihsm/error/type.BoxError.html Demonstrates the basic usage of Box::new to allocate memory on the heap and place a value into it. ```rust let five = Box::new(5); ``` -------------------------------- ### Get Session ID Source: https://docs.rs/yubihsm/latest/src/yubihsm/session/securechannel.rs.html Retrieves the unique identifier for the current secure session. ```APIDOC ## id ### Description Returns the unique identifier of the secure channel (session). ### Method `fn` id(&self) -> session::Id ### Parameters None ### Request Example ```rust // Assuming `session` is an established SecureChannel object let session_id = session.id(); println!("Session ID: {:?}", session_id); ``` ### Response #### Success Response (200) - **session::Id**: The unique ID of the session. #### Response Example ```rust // Example output: Session ID: 1 ``` ``` -------------------------------- ### Box::new_uninit_in Source: https://docs.rs/yubihsm/latest/yubihsm/error/type.BoxError.html Constructs a new box with uninitialized contents in the provided allocator. This is a nightly-only experimental API. ```APIDOC ## Box::new_uninit_in ### Description Constructs a new box with uninitialized contents in the provided allocator. ### Method Associated function (called as `Box::new_uninit_in(alloc)`) ### Parameters - **alloc** (A) - The allocator to use. ### Returns - **Box, A>** - A new box with uninitialized contents. ### Examples ``` #![feature(allocator_api)] use std::alloc::System; let mut five = Box::::new_uninit_in(System); // Deferred initialization: five.write(5); let five = unsafe { five.assume_init() }; assert_eq!(*five, 5) ``` ``` -------------------------------- ### State::new Source: https://docs.rs/yubihsm/latest/src/yubihsm/mockhsm/state.rs.html Initializes a new `State` instance with default values for all fields. ```APIDOC ## State::new ### Description Creates a new instance of the server's mutable interior state. ### Method `State::new()` ### Returns A new `State` struct with default audit options, no active sessions, and empty objects. ``` -------------------------------- ### Get Object Info Source: https://docs.rs/yubihsm/latest/src/yubihsm/client.rs.html Retrieves information about a specific object stored in the HSM. ```APIDOC ## get_object_info ### Description Get information about an object. ### Method Signature ```rust pub fn get_object_info( &self, object_id: object::Id, object_type: object::Type, ) -> Result ``` ### Parameters - **object_id** (object::Id) - The ID of the object. - **object_type** (object::Type) - The type of the object. ``` -------------------------------- ### Profile::new Source: https://docs.rs/yubihsm/latest/yubihsm/setup/struct.Profile.html Creates a new, empty profile. ```APIDOC ## pub fn new() -> Self Create a new empty profile ``` -------------------------------- ### Get Log Entries Source: https://docs.rs/yubihsm/latest/src/yubihsm/client.rs.html Retrieves all audit log entries from the HSM device. ```APIDOC ## get_log_entries ### Description Get audit logs from the HSM device. ### Method Signature ```rust pub fn get_log_entries(&self) -> Result ``` ### Returns - **LogEntries** - A structure containing the log entries. ``` -------------------------------- ### Credentials::new Source: https://docs.rs/yubihsm/latest/src/yubihsm/authentication/credentials.rs.html Constructor for creating a new `Credentials` instance with a specified authentication key ID and authentication key. ```APIDOC ## Credentials::new ### Description Creates a new `Credentials` instance. ### Parameters - **authentication_key_id** (object::Id) - The ID of the key to use for authentication. - **authentication_key** (authentication::Key) - The authentication key. ``` -------------------------------- ### Get Commands Audit Options Source: https://docs.rs/yubihsm/latest/src/yubihsm/audit/commands/get_option.rs.html Retrieves the audit settings for all configured commands. ```APIDOC ## Get Commands Audit Options ### Description Retrieves the audit settings for all commands configured on the YubiHSM. ### Method `get_commands_audit_options()` ### Parameters This method does not take any explicit parameters in the SDK. ### Response - **audit_options** (map) - A map where keys are command identifiers and values are booleans indicating if auditing is enabled for that command. ### Request Example ```rust // Assuming 'client' is an authenticated yubihsm::Client instance let audit_options = client.get_commands_audit_options().await?; ``` ### Response Example ```json { "GenerateRsaKey": true, "SignEcdsa": false, "DecryptAes": true } ``` ``` -------------------------------- ### Connect and Sign with YubiHSM2 via USB Source: https://docs.rs/yubihsm/latest/index.html Example demonstrates connecting to a YubiHSM2 via USB and performing an Ed25519 signature. Ensure the key exists on the HSM before running. Uses default credentials, which should not be used in production. ```rust use yubihsm::{Client, Credentials, UsbConnector}; // Connect to the first YubiHSM 2 we detect let connector = UsbConnector::default(); // Default auth key ID and password for YubiHSM 2 // NOTE: DON'T USE THIS IN PRODUCTION! let credentials = Credentials::default(); // Connect to the HSM and authenticate with the given credentials let mut hsm_client = Client::open(connector, credentials, true).unwrap(); // Note: You'll need to create this key first. Run the following from yubihsm-shell: // `generate asymmetric 0 100 ed25519_test_key 1 asymmetric_sign_eddsa ed25519` let signature = hsm_client.sign_ed25519(100, "Hello, world!").unwrap(); println!("Ed25519 signature: {:?}", signature); ``` -------------------------------- ### Get Command Audit Option Source: https://docs.rs/yubihsm/latest/src/yubihsm/audit/commands/get_option.rs.html Retrieves the audit setting for a specific command. ```APIDOC ## Get Command Audit Option ### Description Retrieves the audit setting for a specific command. ### Method `get_command_audit_option()` ### Parameters This method does not take any explicit parameters in the SDK, but the underlying command requires an `AuditTag` to specify the command. ### Response - **audit_option** (boolean) - Indicates if auditing is enabled for the specified command. ### Request Example ```rust // Assuming 'client' is an authenticated yubihsm::Client instance let command_tag = yubihsm::audit::AuditTag::Command(yubihsm::audit::CommandTag::GenerateRsaKey); let audit_option = client.get_command_audit_option(command_tag).await?; ``` ### Response Example ```json // Example response indicating auditing is enabled for the command true ``` ``` -------------------------------- ### Get S Component Bytes Source: https://docs.rs/yubihsm/latest/yubihsm/ed25519/struct.Signature.html Retrieves the 32-byte array representing the s component of the Ed25519 signature. ```rust pub fn s_bytes(&self) -> &[u8; 32] ``` -------------------------------- ### Create a Zeroed Box Source: https://docs.rs/yubihsm/latest/yubihsm/error/type.BoxError.html This example uses a nightly-only feature to create a Box with memory initialized to zero bytes. It requires `unsafe` to assume initialization. ```rust #![feature(new_zeroed_alloc)] let zero = Box::::new_zeroed(); let zero = unsafe { zero.assume_init() }; assert_eq!(*zero, 0) ``` -------------------------------- ### Create New Credentials Source: https://docs.rs/yubihsm/latest/yubihsm/authentication/struct.Credentials.html Constructs a new `Credentials` instance using an authentication key ID and an authentication key. ```rust pub fn new(authentication_key_id: Id, authentication_key: Key) -> Self ``` -------------------------------- ### Get X-Coordinate Source: https://docs.rs/yubihsm/latest/yubihsm/ecdsa/sec1/type.EncodedPoint.html Retrieves the x-coordinate of the EncodedPoint. Returns None if the point is the identity point. ```rust pub fn x(&self) -> Option<&GenericArray> ``` -------------------------------- ### Get SEC 1 Tag Source: https://docs.rs/yubihsm/latest/yubihsm/ecdsa/sec1/type.EncodedPoint.html Retrieves the SEC 1 tag associated with this EncodedPoint. ```rust pub fn tag(&self) -> Tag ``` -------------------------------- ### Device Initialization Functions Source: https://docs.rs/yubihsm/latest/yubihsm/all.html Functions for initializing the YubiHSM device with a profile. ```APIDOC ## setup::erase_device_and_init_with_profile ### Description Erases the device and initializes it with the specified profile. ### Function Signature `pub fn erase_device_and_init_with_profile(profile: Profile) -> Result<(), setup::Error>` ### Parameters - `profile` (Profile): The profile to initialize the device with. ### Returns - `Result<(), setup::Error>`: Ok if successful, or an error if initialization fails. ``` ```APIDOC ## setup::init_with_profile ### Description Initializes the YubiHSM device with the specified profile without erasing existing data. ### Function Signature `pub fn init_with_profile(profile: Profile) -> Result<(), setup::Error>` ### Parameters - `profile` (Profile): The profile to initialize the device with. ### Returns - `Result<(), setup::Error>`: Ok if successful, or an error if initialization fails. ``` -------------------------------- ### Key::create Source: https://docs.rs/yubihsm/latest/yubihsm/wrap/struct.Key.html Creates this wrap key within the HSM using the provided client. ```APIDOC ## Key::create ### Description Create this key within the HSM ### Signature `pub fn create(&self, client: &Client) -> Result<(), Error>` ``` -------------------------------- ### Get Encoded Point Length Source: https://docs.rs/yubihsm/latest/yubihsm/ecdsa/sec1/type.EncodedPoint.html Retrieves the length of the serialized encoded point in bytes. ```rust pub fn len(&self) -> usize ``` -------------------------------- ### Getting Serial Numbers Source: https://docs.rs/yubihsm/latest/yubihsm/connector/usb/struct.Devices.html Retrieve the serial numbers of all connected YubiHSM 2 devices. ```APIDOC ## serial_numbers ### Description Return the serial numbers of all connected YubiHSM 2s. ### Method `Devices::serial_numbers() -> Result, Error>` ``` -------------------------------- ### Open Secure Channel with Authentication Source: https://docs.rs/yubihsm/latest/src/yubihsm/session/securechannel.rs.html Initiates a secure channel by performing challenge-response authentication and establishing session keys. Requires a connector and credentials. ```rust pub(crate) fn open( connector: &Connector, credentials: &Credentials, ) -> Result { let host_challenge = Challenge::new(); let command_message = command::Message::from(&CreateSessionCommand { authentication_key_id: credentials.authentication_key_id, host_challenge, }); let uuid = command_message.uuid; let response_body = connector.send_message(uuid, command_message.into())?; let response_message = response::Message::parse(response_body)?; if response_message.is_err() { match device::ErrorKind::from_response_message(&response_message) { Some(device::ErrorKind::ObjectNotFound) => fail!( ErrorKind::AuthenticationError, "auth key not found: 0x{:04x}", credentials.authentication_key_id ), Some(kind) => return Err(kind.into()), None => fail!( ErrorKind::ResponseError, "HSM error: {:?}", response_message.code ) } } // TODO: finish implementation unimplemented!() } ``` -------------------------------- ### Get Session ID Source: https://docs.rs/yubihsm/latest/src/yubihsm/session/securechannel.rs.html Retrieves the unique identifier for the current secure channel session. ```rust /// Get the channel (i.e. session) ID pub fn id(&self) -> session::Id { self.id } ``` -------------------------------- ### Get Command Audit Option Source: https://docs.rs/yubihsm/latest/src/yubihsm/client.rs.html Retrieves the audit policy setting for a specific command. ```APIDOC ## get_command_audit_option ### Description Get the audit policy setting for a particular command. ### Method Signature ```rust pub fn get_command_audit_option(&self, command: command::Code) -> Result ``` ### Parameters - **command** (command::Code) - The command code to check the audit policy for. ### Returns - **AuditOption** - The audit option setting for the command (defaults to Off if not found). ``` -------------------------------- ### From for usize Implementation Source: https://docs.rs/yubihsm/latest/yubihsm/setup/report/struct.Version.html Allows conversion of a Version instance into a usize. ```APIDOC ### impl From for usize #### fn from(version: Version) -> usize Converts to this type from the input type. ``` -------------------------------- ### Create Secure Channel Pair for Testing Source: https://docs.rs/yubihsm/latest/src/yubihsm/session/securechannel.rs.html Sets up a pair of `SecureChannel` instances for testing purposes. It derives authentication keys, generates challenges, and performs the session authentication handshake. ```rust fn create_channel_pair() -> (SecureChannel, SecureChannel) { let authentication_key = authentication::Key::derive_from_password(PASSWORD); let host_challenge = Challenge::from_slice(HOST_CHALLENGE); let card_challenge = Challenge::from_slice(CARD_CHALLENGE); let session_id = session::Id::from_u8(0).unwrap(); // Create channels let mut host_channel = SecureChannel::new( session_id, &authentication_key, host_challenge, card_challenge, ); let mut card_channel = SecureChannel::new( session_id, &authentication_key, host_challenge, card_challenge, ); // Auth host to card let auth_command = host_channel.authenticate_session().unwrap(); let auth_response = card_channel .verify_authenticate_session(&auth_command) .unwrap(); host_channel .finish_authenticate_session(&auth_response) .unwrap(); (host_channel, card_channel) } ``` -------------------------------- ### HsmSession Get Card Cryptogram Source: https://docs.rs/yubihsm/latest/src/yubihsm/mockhsm/session.rs.html Obtains the card cryptogram from the secure channel for the session. ```rust pub fn card_cryptogram(&self) -> Cryptogram { self.channel.card_cryptogram() } ``` -------------------------------- ### Create Minimal Import Parameters Source: https://docs.rs/yubihsm/latest/src/yubihsm/object/put.rs.html Provides a constructor to create a minimal `import::Params` instance with a given object ID and algorithm. Default values are used for label, domains, and capabilities. ```rust impl Params { /// Create minimal `import::Params` using the given `object::Id` and algorithm pub fn new(id: object::Id, algorithm: Algorithm) -> Self { Self { id, label: object::Label::default(), domains: Domain::empty(), capabilities: Capability::empty(), algorithm, } } } ``` -------------------------------- ### Get Y-Coordinate Source: https://docs.rs/yubihsm/latest/yubihsm/ecdsa/sec1/type.EncodedPoint.html Retrieves the y-coordinate of the EncodedPoint. Returns None if the point is compressed or the identity point. ```rust pub fn y(&self) -> Option<&GenericArray> ``` -------------------------------- ### Get Encoded Point as Byte Slice Source: https://docs.rs/yubihsm/latest/yubihsm/ecdsa/sec1/type.EncodedPoint.html Provides a byte slice view of the serialized EncodedPoint. ```rust pub fn as_bytes(&self) -> &[u8] ``` -------------------------------- ### Set Wrap Keys for Initial Provisioning Source: https://docs.rs/yubihsm/latest/yubihsm/setup/struct.Profile.html Define the wrap keys that will be initially provisioned on the YubiHSM 2. Accepts any iterator that yields `Key` items. ```rust pub fn wrap_keys(self, keys: I) -> Self where I: IntoIterator, ``` -------------------------------- ### Profile::roles Source: https://docs.rs/yubihsm/latest/yubihsm/setup/struct.Profile.html Sets the initial roles to provision. ```APIDOC ## pub fn roles(self, roles: I) -> Self where I: IntoIterator, Set the initial roles to provision ``` -------------------------------- ### Get Device Address Source: https://docs.rs/yubihsm/latest/yubihsm/connector/usb/struct.Device.html Retrieves the address of the USB device on its bus. This is a simple getter method. ```rust pub fn address(&self) -> u8 ``` -------------------------------- ### Define a YubiHSM 2 Provisioning Profile Source: https://docs.rs/yubihsm/latest/yubihsm/setup/struct.Profile.html Use the Profile struct to declaratively define the provisioning settings for a YubiHSM 2 device. This struct is available when the `setup` crate feature is enabled. ```rust pub struct Profile { /* private fields */ } ``` -------------------------------- ### Get YubiHSM Session Duration Source: https://docs.rs/yubihsm/latest/src/yubihsm/session.rs.html Calculates the total time elapsed since the session was created. ```rust pub fn duration(&self) -> Duration { Instant::now().duration_since(self.created_at) } ```