### Standard Feature Combination Example Source: https://github.com/rustcrypto/ssh/blob/master/_autodocs/modules-and-exports.md Example Cargo.toml configuration for the recommended standard SSH setup, relying on default features for most crates. ```toml ssh-cipher = "..." # Default features: aes, tdes ssh-encoding = "..." # Default features: alloc, base64 ssh-key = "..." # Default features: ed25519, alloc, std ``` -------------------------------- ### Full Featured Combination Example Source: https://github.com/rustcrypto/ssh/blob/master/_autodocs/modules-and-exports.md Example Cargo.toml configuration for a full-featured SSH setup, explicitly enabling all desired features. ```toml ssh-cipher = { version = "...", features = ["aes", "tdes", "chacha20poly1305"] } ssh-encoding = { version = "...", features = ["alloc", "base64", "pem", "derive", "digest"] } ssh-key = { version = "...", features = ["ed25519", "ecdsa", "rsa", "dsa", "encryption", "rand_core", "ppk", "serde", "std"] } ``` -------------------------------- ### Minimal Feature Combination Example Source: https://github.com/rustcrypto/ssh/blob/master/_autodocs/modules-and-exports.md Example Cargo.toml configuration for a minimal SSH setup, disabling default features and enabling specific ones. ```toml ssh-cipher = { version = "...", default-features = false, features = ["aes"] } ssh-encoding = { version = "...", default-features = false, features = ["alloc"] } ssh-key = { version = "...", default-features = false, features = ["ed25519"] } ``` -------------------------------- ### Algorithm Detection Example Source: https://github.com/rustcrypto/ssh/blob/master/_autodocs/api-reference/ssh-key-algorithm.md An example demonstrating how to detect and handle different SSH key algorithms based on the public key. ```APIDOC ## Example: Algorithm Detection ```rust use ssh_key::{PublicKey, Algorithm, HashAlg}; let key = PublicKey::from_openssh(key_str)?; match key.algorithm() { Algorithm::Ed25519 => { println!("Ed25519 key - recommended"); } Algorithm::Rsa { hash } => { match hash { Some(HashAlg::Sha256) => println!("RSA with SHA-256"), Some(HashAlg::Sha512) => println!("RSA with SHA-512"), None => println!("RSA (legacy sha1)"), } } Algorithm::Ecdsa { curve } => { println!("ECDSA with {}", curve.as_str()); } Algorithm::Dsa => { println!("DSA - deprecated"); } Algorithm::SkEd25519 => { println!("FIDO/U2F Ed25519 key"); } Algorithm::SkEcdsaSha2NistP256 => { println!("FIDO/U2F ECDSA P-256 key"); } #[cfg(feature = "alloc")] Algorithm::Other(name) => { println!("Unknown algorithm: {}", name); } } ``` ``` -------------------------------- ### HashAlg Method Example Source: https://github.com/rustcrypto/ssh/blob/master/_autodocs/api-reference/ssh-key-algorithm.md Demonstrates how to get the digest size in bytes for SHA-256 and SHA-512 hash algorithms. ```rust use ssh_key::HashAlg; assert_eq!(HashAlg::Sha256.digest_size(), 32); assert_eq!(HashAlg::Sha512.digest_size(), 64); ``` -------------------------------- ### Algorithm Detection Example Source: https://github.com/rustcrypto/ssh/blob/master/_autodocs/api-reference/ssh-key-algorithm.md Example of detecting the algorithm of a PublicKey and handling different algorithm types, including RSA with specific hash algorithms and deprecated DSA. ```rust use ssh_key::{PublicKey, Algorithm, HashAlg}; let key = PublicKey::from_openssh(key_str)?; match key.algorithm() { Algorithm::Ed25519 => { println!("Ed25519 key - recommended"); } Algorithm::Rsa { hash } => { match hash { Some(HashAlg::Sha256) => println!("RSA with SHA-256"), Some(HashAlg::Sha512) => println!("RSA with SHA-512"), None => println!("RSA (legacy sha1)"), } } Algorithm::Ecdsa { curve } => { println!("ECDSA with {}", curve.as_str()); } Algorithm::Dsa => { println!("DSA - deprecated"); } Algorithm::SkEd25519 => { println!("FIDO/U2F Ed25519 key"); } Algorithm::SkEcdsaSha2NistP256 => { println!("FIDO/U2F ECDSA P-256 key"); } #[cfg(feature = "alloc")] Algorithm::Other(name) => { println!("Unknown algorithm: {}", name); } } ``` -------------------------------- ### DigestWriter Usage Example Source: https://github.com/rustcrypto/ssh/blob/master/_autodocs/api-reference/ssh-encoding.md Example demonstrating how to use `DigestWriter` to encode data and compute a SHA256 hash simultaneously. Ensure the `digest` feature is enabled. ```rust use ssh_encoding::{Encode, DigestWriter}; use sha2::{Sha256, Digest}; let mut digest = Sha256::new(); let mut writer = DigestWriter(&mut digest); // Encode data while computing hash some_value.encode(&mut writer)?; let hash = digest.finalize(); ``` -------------------------------- ### Usage of SSH Derive Macros Source: https://github.com/rustcrypto/ssh/blob/master/_autodocs/modules-and-exports.md Example demonstrating how to derive Encode and Decode traits for a struct and an enum using ssh-derive. ```rust use ssh_encoding::{Encode, Decode}; #[derive(Encode, Decode)] struct Message { field1: String, field2: u32, } #[derive(Encode, Decode)] #[repr(u8)] enum Type { Variant1 = 1, Variant2 = 2, } ``` -------------------------------- ### String Encoding Example Source: https://github.com/rustcrypto/ssh/blob/master/_autodocs/api-reference/ssh-encoding.md Shows how a Rust String can be directly encoded as an SSH string type using the Encode trait. Requires the 'alloc' feature. ```rust use ssh_encoding::{Encode, Writer}; use alloc::string::String; // String directly encodes as SSH string type let mut output = Vec::new(); let s = String::from("hello"); // s.encode(&mut output)?; ``` -------------------------------- ### Check SSH Public Key Algorithm and Route Source: https://github.com/rustcrypto/ssh/blob/master/_autodocs/usage-patterns.md Provides an example of how to inspect an SSH public key's algorithm and hash type, then conditionally execute code based on the detected algorithm. Useful for handling different key types appropriately. ```rust use ssh_key::{PublicKey, Algorithm, HashAlg}; let key = PublicKey::from_openssh(key_str)?; match key.algorithm() { Algorithm::Ed25519 => { println!("Ed25519 - modern algorithm"); } Algorithm::Rsa { hash } => { match hash { Some(HashAlg::Sha256) => println!("RSA-SHA2-256"), Some(HashAlg::Sha512) => println!("RSA-SHA2-512"), None => println!("RSA-SHA1 (legacy)"), } } Algorithm::Ecdsa { curve } => { println!("ECDSA with {}", curve.as_str()); } Algorithm::Dsa => println!("DSA (deprecated)"), _ => println!("Other algorithm"), } ``` -------------------------------- ### Get Certificate Principals Source: https://github.com/rustcrypto/ssh/blob/master/_autodocs/api-reference/ssh-key-certificate.md Iterates over and prints all authorized principals for a given certificate. ```rust for principal in cert.principals() { println!("Authorized: {}", principal); } ``` -------------------------------- ### Get SSH Key Fingerprint Source: https://github.com/rustcrypto/ssh/blob/master/_autodocs/api-reference/ssh-key-public.md Demonstrates how to retrieve the SHA-256 fingerprint of an SSH key and print it. Also shows how to generate and print the Randomart ASCII art representation of the fingerprint. ```rust use ssh_key::HashAlg; let fp = key.fingerprint(HashAlg::Sha256); println!("Fingerprint: {}", fp); // Output: SHA256:Nh0Me49Zh9fDw/VYUfq43IJmI1T+XrjiYONPND8GzaM println!("Randomart:\n{}", fp.randomart()?); ``` -------------------------------- ### Get Key and IV Size Source: https://github.com/rustcrypto/ssh/blob/master/_autodocs/api-reference/ssh-cipher.md The `key_and_iv_size` method returns the key and initialization vector size in bytes for a cipher. It returns `None` for `Cipher::None`. ```rust use ssh_cipher::Cipher; let (key_size, iv_size) = Cipher::Aes256Ctr.key_and_iv_size().unwrap(); assert_eq!(key_size, 32); assert_eq!(iv_size, 16); ``` -------------------------------- ### Get the key derivation function (KDF) used Source: https://github.com/rustcrypto/ssh/blob/master/_autodocs/api-reference/ssh-key-private.md Retrieves details about the key derivation function used for this private key. ```rust #[must_use] pub fn kdf(&self) -> &Kdf ``` -------------------------------- ### Get Private Key Comment Source: https://github.com/rustcrypto/ssh/blob/master/_autodocs/api-reference/ssh-key-private.md Retrieves the comment associated with the private key. Requires the 'alloc' Cargo feature. ```rust #[cfg(feature = "alloc")] #[must_use] pub fn comment(&self) -> &str ``` -------------------------------- ### Cipher::key_and_iv_size Source: https://github.com/rustcrypto/ssh/blob/master/_autodocs/api-reference/ssh-cipher.md Get the key and initialization vector size for this cipher in bytes. Returns a tuple of (key_size, iv_size) or None for Cipher::None. ```APIDOC ## Cipher::key_and_iv_size Get the key and initialization vector size for this cipher in bytes. ```rust #[must_use] pub fn key_and_iv_size(self) -> Option<(usize, usize)> ``` ### Return Type `Option<(usize, usize)>` — Tuple of (key_size, iv_size) in bytes, or None for `Cipher::None` ### Returns None for: `Cipher::None` | Cipher | |----------| | `Aes128Cbc/Ctr/Gcm` | 16 bytes | 16/12 bytes | | `Aes192Cbc/Ctr` | 24 bytes | 16 bytes | | `Aes256Cbc/Ctr/Gcm` | 32 bytes | 16/12 bytes | | `ChaCha20Poly1305` | 32 bytes | 8 bytes | | `TdesCbc` | 24 bytes | 8 bytes | ### Example: ```rust use ssh_cipher::Cipher; let (key_size, iv_size) = Cipher::Aes256Ctr.key_and_iv_size().unwrap(); assert_eq!(key_size, 32); assert_eq!(iv_size, 16); ``` ``` -------------------------------- ### Validating SSH Certificates Before Trust Source: https://github.com/rustcrypto/ssh/blob/master/_autodocs/usage-patterns.md Provides an example of validating an SSH certificate against trusted Certificate Authorities, checking for expiration, and verifying expected principals before trusting it. ```rust use ssh_key::{Certificate, Fingerprint}; use std::time::SystemTime; let cert = Certificate::from_openssh(cert_str)?; let trusted_cas = [/* ... */]; // Always validate before using certificate cert.validate(&trusted_cas)?; // Check it hasn't expired assert!(cert.is_valid_at( SystemTime::now() .duration_since(SystemTime::UNIX_EPOCH)? .as_secs() )); // Verify expected principal assert!(cert.principals().contains(&"alice".to_string())); ``` -------------------------------- ### Get Public Key Algorithm Source: https://github.com/rustcrypto/ssh/blob/master/_autodocs/api-reference/ssh-key-certificate.md Retrieves the public key algorithm used by the certificate. This accessor method returns the `Algorithm` enum variant. ```rust #[must_use] pub fn algorithm(&self) -> Algorithm ``` -------------------------------- ### SSH Derive Macro Attributes Example Source: https://github.com/rustcrypto/ssh/blob/master/_autodocs/api-reference/ssh-encoding.md Demonstrates using `#[ssh(length_prefixed)]` and `#[repr(u8)]` attributes with derive macros for custom encoding behavior and enum discriminants. ```rust use ssh_encoding::{Decode, Encode}; #[derive(Encode, Decode, Debug, PartialEq)] #[ssh(length_prefixed)] struct KeyData { key_type: String, public_key: Vec, } #[derive(Encode, Decode, Debug, PartialEq)] #[repr(u8)] enum Message { Init = 20, Newkeys = 21, } ``` -------------------------------- ### Get Associated Hash Algorithm for SSH Keys Source: https://github.com/rustcrypto/ssh/blob/master/_autodocs/usage-patterns.md Shows how to retrieve the default or specified hash algorithm associated with an SSH key algorithm. This is helpful for understanding the cryptographic properties of a key. ```rust use ssh_key::Algorithm; let alg = Algorithm::Ed25519; let hash_alg = alg.associated_hash_alg(); // Or for RSA with specific hash let rsa_alg = Algorithm::Rsa { hash: Some(ssh_key::HashAlg::Sha256) }; ``` -------------------------------- ### Recommended SSH Dependencies Source: https://github.com/rustcrypto/ssh/blob/master/_autodocs/README.md Sets up recommended default dependencies for SSH crates, including common encryption and key algorithm support. ```toml [dependencies] ssh-cipher = "0.7" ssh-encoding = "0.2" ssh-key = "0.6" ``` -------------------------------- ### Create a New PublicKey Source: https://github.com/rustcrypto/ssh/blob/master/_autodocs/api-reference/ssh-key-public.md Use PublicKey::new to create a new public key instance. This requires providing the key data and an optional human-readable comment. ```rust use ssh_key::{PublicKey, public::KeyData}; // Requires getting key_data from some algorithm let key = PublicKey::new(key_data, "user@example.com"); ``` -------------------------------- ### Cipher::block_size Source: https://github.com/rustcrypto/ssh/blob/master/_autodocs/api-reference/ssh-cipher.md Get the block size for this cipher in bytes. Returns the block size in bytes. ```APIDOC ## Cipher::block_size Get the block size for this cipher in bytes. ```rust #[must_use] pub fn block_size(self) -> usize ``` ### Return Type `usize` — Block size in bytes | Cipher Type | |-----------| | AES-CBC, AES-CTR, AES-GCM | 16 bytes | | ChaCha20Poly1305, 3DES-CBC, None | 8 bytes | ### Example: ```rust use ssh_cipher::Cipher; assert_eq!(Cipher::Aes256Cbc.block_size(), 16); assert_eq!(Cipher::ChaCha20Poly1305.block_size(), 8); ``` ``` -------------------------------- ### Create Stateful Encryptor with AES-256-CBC Source: https://github.com/rustcrypto/ssh/blob/master/_autodocs/usage-patterns.md Demonstrates how to create a stateful encryptor for streaming data using AES-256-CBC mode. Requires a cipher, key, and initialization vector. ```rust use ssh_cipher::Cipher; let cipher = Cipher::Aes256Cbc; let key = [0u8; 32]; let iv = [0u8; 16]; // Create stateful encryptor let mut encryptor = cipher.encryptor::(&key, &iv)?; // Can encrypt multiple blocks // encryptor.encrypt_blocks(&mut blocks); ``` -------------------------------- ### EcdsaCurve Methods Source: https://github.com/rustcrypto/ssh/blob/master/_autodocs/api-reference/ssh-key-algorithm.md Provides methods for interacting with ECDSA curves, including getting their string names and key sizes. ```APIDOC ## EcdsaCurve Methods ### as_str() → &'static str Get curve name ("nistp256", "nistp384", "nistp521") ### key_size() → usize Get key size in bits (256, 384, 521) ### Example: ```rust use ssh_key::EcdsaCurve; assert_eq!(EcdsaCurve::NistP256.as_str(), "nistp256"); assert_eq!(EcdsaCurve::NistP256.key_size(), 256); ``` ``` -------------------------------- ### Read SSH Public and Private Keys from Files Source: https://github.com/rustcrypto/ssh/blob/master/_autodocs/usage-patterns.md Demonstrates how to load SSH public, private, and certificate keys from files using their respective `from_openssh` methods. Assumes keys are stored in OpenSSH format. ```rust use ssh_key::{PrivateKey, PublicKey}; use std::path::Path; // Public key let pub_key = PublicKey::from_openssh( std::fs::read_to_string("id_ed25519.pub")? )?; // Private key let priv_key = PrivateKey::from_openssh( std::fs::read_to_string("id_ed25519")? )?; // Certificate let cert = ssh_key::Certificate::from_openssh( std::fs::read_to_string("id_ed25519-cert.pub")? )?; ``` -------------------------------- ### Build and Sign an SSH Certificate Source: https://github.com/rustcrypto/ssh/blob/master/_autodocs/api-reference/ssh-key-certificate.md Constructs a new user certificate with specified principals and validity, then signs it using a CA private key. Ensure the CA private key and user public key are loaded correctly. ```rust use ssh_key::certificate::{Builder, CertType}; use ssh_key::PrivateKey; let ca_key = PrivateKey::from_openssh(ca_pem)?; let user_pub_key = PublicKey::from_openssh(user_key_str)?; let cert = Builder::new( 1, CertType::User, "user-key-2024".to_string(), user_pub_key ) .principal("alice".to_string()) .principal("alice@example.com".to_string()) .valid_after(1704067200) // 2024-01-01 .valid_before(1735689600) // 2025-01-01 .sign(&ca_key.signing_key())?; ``` -------------------------------- ### PublicKey::new Source: https://github.com/rustcrypto/ssh/blob/master/_autodocs/api-reference/ssh-key-public.md Creates a new public key instance with specified key data and an optional comment. ```APIDOC ## PublicKey::new ### Description Create a new public key with optional comment. ### Method `#[cfg(feature = "alloc")] pub fn new(key_data: KeyData, comment: impl Into) -> Self` ### Parameters #### Function Parameters - **key_data** (KeyData) - Required - The actual key data (algorithm-specific) - **comment** (impl Into) - Required - Optional human-readable comment (usually email) ### Return Type `PublicKey` - Newly created public key ### Example ```rust use ssh_key::{PublicKey, public::KeyData}; // Requires getting key_data from some algorithm let key = PublicKey::new(key_data, "user@example.com"); ``` ``` -------------------------------- ### Get Cipher String Identifier Source: https://github.com/rustcrypto/ssh/blob/master/_autodocs/api-reference/ssh-cipher.md Use `Cipher::as_str` to retrieve the SSH protocol name for a given cipher algorithm. ```rust use ssh_cipher::Cipher; assert_eq!(Cipher::Aes256Ctr.as_str(), "aes256-ctr"); assert_eq!(Cipher::ChaCha20Poly1305.as_str(), "chacha20-poly1305@openssh.com"); ``` -------------------------------- ### Get Associated Hash Algorithm Source: https://github.com/rustcrypto/ssh/blob/master/_autodocs/api-reference/ssh-key-algorithm.md Retrieves the default hash algorithm associated with an SSH key algorithm for signing operations. ```rust use ssh_key::Algorithm; // Example usage would involve calling associated_hash_alg on an Algorithm instance. ``` -------------------------------- ### Minimal Dependencies for No-std SSH Source: https://github.com/rustcrypto/ssh/blob/master/_autodocs/usage-patterns.md Provides a sample `Cargo.toml` configuration for setting up a no-std environment with minimal dependencies for SSH functionalities. It specifies versions and disables default features for core crates like `ssh-cipher`, `ssh-encoding`, and `ssh-key`, enabling only necessary features like `aes` and `ed25519`. ```toml [dependencies] ssh-cipher = { version = "0.7", default-features = false, features = ["aes"] } ssh-encoding = { version = "0.2", default-features = false } ssh-key = { version = "0.6", default-features = false, features = ["ed25519"] } ``` -------------------------------- ### Derive Decode Macro Usage Source: https://github.com/rustcrypto/ssh/blob/master/_autodocs/api-reference/ssh-encoding.md Example of using the `#[derive(Decode)]` procedural macro to automatically implement the Decode trait for a struct. ```rust #[derive(Decode)] struct MyMessage { field1: String, field2: u32, } ``` -------------------------------- ### Derive Encode Macro Usage Source: https://github.com/rustcrypto/ssh/blob/master/_autodocs/api-reference/ssh-encoding.md Example of using the `#[derive(Encode)]` procedural macro to automatically implement the Encode trait for a struct. ```rust #[derive(Encode)] struct MyMessage { field1: String, field2: u32, } ``` -------------------------------- ### JSON Serialization and Deserialization Source: https://github.com/rustcrypto/ssh/blob/master/_autodocs/usage-patterns.md Shows how to serialize a PublicKey to JSON and deserialize it back, using the OpenSSH format for serialization. Requires the `serde` feature. ```rust use ssh_key::PublicKey; use serde_json::json; let key = PublicKey::from_openssh(key_str)?; // Serialize to JSON (uses OpenSSH format) let json = serde_json::to_string(&key)?; // Deserialize from JSON let deserialized: PublicKey = serde_json::from_str(&json)? ``` -------------------------------- ### Cipher::as_str Source: https://github.com/rustcrypto/ssh/blob/master/_autodocs/api-reference/ssh-cipher.md Get the string identifier for this cipher algorithm. Returns the SSH protocol name for this cipher as a static string slice. ```APIDOC ## Cipher::as_str Get the string identifier for this cipher algorithm. ```rust #[must_use] pub fn as_str(self) -> &'static str ``` ### Return Type `&'static str` — SSH protocol name for this cipher ### Example: ```rust use ssh_cipher::Cipher; assert_eq!(Cipher::Aes256Ctr.as_str(), "aes256-ctr"); assert_eq!(Cipher::ChaCha20Poly1305.as_str(), "chacha20-poly1305@openssh.com"); ``` ``` -------------------------------- ### Get SSH Certificate Type String Source: https://github.com/rustcrypto/ssh/blob/master/_autodocs/api-reference/ssh-key-algorithm.md Converts an `Algorithm` enum variant into its corresponding OpenSSH certificate type identifier string. ```rust use ssh_key::Algorithm; assert_eq!( Algorithm::Ed25519.to_certificate_type(), "ssh-ed25519-cert-v01@openssh.com" ); ``` -------------------------------- ### Base64Writer::new Constructor Source: https://github.com/rustcrypto/ssh/blob/master/_autodocs/api-reference/ssh-encoding.md Constructs a new `Base64Writer`. Returns an error if the output buffer is too small. ```rust pub fn new(output: &'a mut [u8]) -> Result ``` -------------------------------- ### Algorithm Parsing from String Source: https://github.com/rustcrypto/ssh/blob/master/_autodocs/api-reference/ssh-key-algorithm.md Demonstrates how to parse an SSH algorithm from its string representation using the FromStr implementation. ```rust use std::str::FromStr; use ssh_key::Algorithm; let alg = Algorithm::from_str("ssh-ed25519")?; ``` -------------------------------- ### Get Standard SSH Algorithm String Source: https://github.com/rustcrypto/ssh/blob/master/_autodocs/api-reference/ssh-key-algorithm.md Converts an `Algorithm` enum variant back into its standard SSH identifier string representation. ```rust use ssh_key::Algorithm; assert_eq!(Algorithm::Ed25519.as_str(), "ssh-ed25519"); assert_eq!(Algorithm::Dsa.as_str(), "ssh-dss"); assert_eq!( Algorithm::Rsa { hash: Some(HashAlg::Sha256) }.as_str(), "rsa-sha2-256" ); ``` -------------------------------- ### Create New Unencrypted Private Key Source: https://github.com/rustcrypto/ssh/blob/master/_autodocs/api-reference/ssh-key-private.md Use `PrivateKey::new` to create a new unencrypted private key with provided key data and a comment. This method requires the `alloc` feature. ```rust use ssh_key::PrivateKey; let key = PrivateKey::new(keypair_data, "user@example.com")?; ``` -------------------------------- ### Get Cipher Block Size Source: https://github.com/rustcrypto/ssh/blob/master/_autodocs/api-reference/ssh-cipher.md The `block_size` method returns the block size in bytes for a given cipher. This is relevant for block cipher modes. ```rust use ssh_cipher::Cipher; assert_eq!(Cipher::Aes256Cbc.block_size(), 16); assert_eq!(Cipher::ChaCha20Poly1305.block_size(), 8); ``` -------------------------------- ### Signature Recommendations Source: https://github.com/rustcrypto/ssh/blob/master/_autodocs/api-reference/ssh-key-algorithm.md Recommendations for choosing hash algorithms when signing with different SSH key algorithms, highlighting preferred and deprecated options. ```APIDOC ## Signature Recommendations | Algorithm | Hash | Status | Recommendation | |-----------|------|--------|-----------------| | Ed25519 | N/A | ✅ | **Use for new keys** | | ECDSA P-256 | SHA-256 | ⚠️ | Only if required | | ECDSA P-384 | SHA-384 | ⚠️ | Only if required | | ECDSA P-521 | SHA-512 | ⚠️ | Only if required | | RSA | SHA-256 | ⚠️ | Migrate away | | RSA | SHA-512 | ⚠️ | Migrate away | | DSA | SHA-1 | ❌ | **Deprecated** | ``` -------------------------------- ### Storing SSH Fingerprints in Config Files Source: https://github.com/rustcrypto/ssh/blob/master/_autodocs/usage-patterns.md Illustrates storing SSH fingerprints in configuration files using Serde for serialization and deserialization. Requires the `serde` feature. ```rust use ssh_key::{PublicKey, Fingerprint}; use serde::{Deserialize, Serialize}; #[derive(Serialize, Deserialize)] struct Config { trusted_keys: Vec, authorized_principals: Vec, } let config = Config { trusted_keys: vec![], authorized_principals: vec!["alice".to_string()], }; let yaml = serde_yaml::to_string(&config)? ``` -------------------------------- ### Public Module: Signature Source: https://github.com/rustcrypto/ssh/blob/master/_autodocs/modules-and-exports.md Handles SSH signatures for signing and verifying messages. Requires the `alloc` feature. ```APIDOC ## Module: signature (requires `alloc`) SSH signatures for signing/verifying messages. ### Struct: `Signature` Represents an SSH signature. ### Struct: `SigningKey` Represents a key used for signing. ``` -------------------------------- ### Get the cipher used to encrypt the private key Source: https://github.com/rustcrypto/ssh/blob/master/_autodocs/api-reference/ssh-key-private.md Returns the encryption cipher used for this private key. Returns Cipher::None if the key is not encrypted. ```rust #[must_use] pub fn cipher(&self) -> Cipher ``` -------------------------------- ### OptionsMap Structure Source: https://github.com/rustcrypto/ssh/blob/master/_autodocs/types.md Represents a map for storing critical or non-critical certificate options and extensions. ```rust pub struct OptionsMap { // Implementation details } ``` -------------------------------- ### HashAlg Enum Source: https://github.com/rustcrypto/ssh/blob/master/_autodocs/api-reference/ssh-key-algorithm.md Represents supported hash algorithms for key derivation and signatures. Includes methods to get the algorithm's name and digest size. ```APIDOC ## HashAlg Enum Hash algorithms for key derivation and signatures. ```rust #[derive(Copy, Clone, Debug, Eq, Hash, PartialEq)] #[non_exhaustive] pub enum HashAlg { /// SHA-256 Sha256, /// SHA-512 Sha512, } ``` ### HashAlg Methods **as_str() → &'static str** — Get name ("sha256" or "sha512") **digest_size() → usize** — Get digest size in bytes (32 or 64) ### Example: ```rust use ssh_key::HashAlg; assert_eq!(HashAlg::Sha256.digest_size(), 32); assert_eq!(HashAlg::Sha512.digest_size(), 64); ``` ``` -------------------------------- ### SigningKey for SSH Private Key Operations Source: https://github.com/rustcrypto/ssh/blob/master/_autodocs/types.md A wrapper for performing signing operations using an SSH private key. Requires the 'alloc' feature and contains implementation details. ```rust pub struct SigningKey { // Implementation details } ``` -------------------------------- ### Avoiding Logging Private Keys Source: https://github.com/rustcrypto/ssh/blob/master/_autodocs/usage-patterns.md Highlights security best practices by showing which methods should NOT be used to log private keys, as they can expose sensitive material. Instead, use methods that confirm loading without revealing the key. ```rust use ssh_key::PrivateKey; let key = PrivateKey::from_openssh(pem_data)?; // DO NOT: // println!("{:?}", key); // Logs entire key structure // eprintln!("{}", key); // Might expose material // DO: println!("Loaded key"); ``` -------------------------------- ### Displaying SSH Errors Source: https://github.com/rustcrypto/ssh/blob/master/_autodocs/errors.md Shows how to use the `Display` trait to get human-readable error messages for SSH-related errors. This is useful for logging or user feedback. ```rust let key = PrivateKey::from_openssh(data)?; // Error messages are human-readable println!("{}", error); // Outputs descriptive error message ``` -------------------------------- ### AuthorizedKeys Parser for OpenSSH Format Source: https://github.com/rustcrypto/ssh/blob/master/_autodocs/types.md A parser for the OpenSSH `authorized_keys` file format. Contains implementation details. ```rust pub struct AuthorizedKeys { // Implementation details } ``` -------------------------------- ### Access PublicKey Key Data Source: https://github.com/rustcrypto/ssh/blob/master/_autodocs/api-reference/ssh-key-public.md Use PublicKey::key_data to get an immutable reference to the underlying key data. This allows inspection of algorithm-specific key components. ```rust let key_data = key.key_data(); if let Some(ed25519) = key_data.ed25519() { // Process Ed25519 key } ``` -------------------------------- ### Base64Reader::new Constructor Source: https://github.com/rustcrypto/ssh/blob/master/_autodocs/api-reference/ssh-encoding.md Constructs a new `Base64Reader`. Returns an error if the input is not valid Base64. ```rust pub fn new(encoded: &[u8]) -> Result ``` -------------------------------- ### EcdsaCurve Enum Definition and Usage Source: https://github.com/rustcrypto/ssh/blob/master/_autodocs/api-reference/ssh-key-algorithm.md Defines the supported NIST elliptic curves for ECDSA keys and provides methods to get their string names and key sizes. ```rust use ssh_key::EcdsaCurve; assert_eq!(EcdsaCurve::NistP256.as_str(), "nistp256"); assert_eq!(EcdsaCurve::NistP256.key_size(), 256); ``` -------------------------------- ### Minimal SSH Dependencies Source: https://github.com/rustcrypto/ssh/blob/master/_autodocs/README.md Configures minimal dependencies for SSH crates, enabling specific features like AES encryption and Ed25519 key support. ```toml [dependencies] ssh-cipher = { version = "0.7", default-features = false, features = ["aes"] } ssh-encoding = { version = "0.2", default-features = false, features = ["alloc"] } ssh-key = { version = "0.6", default-features = false, features = ["ed25519"] } ``` -------------------------------- ### Encrypt Private Key with Password Source: https://github.com/rustcrypto/ssh/blob/master/_autodocs/usage-patterns.md Encrypts a private key using a password and a random number generator. The encrypted key can then be saved to a file. ```rust use ssh_key::PrivateKey; use ssh_key::rand_core::OsRng; let mut rng = OsRng; let key = PrivateKey::from_openssh(pem_data)?; // Encrypt with password let encrypted = key.encrypt(&mut rng, "my-secret-password")?; // Save to file encrypted.write_openssh("id_ed25519.enc")?; ``` -------------------------------- ### Display Implementation for Algorithm Source: https://github.com/rustcrypto/ssh/blob/master/_autodocs/api-reference/ssh-key-algorithm.md Allows converting an SSH algorithm into its string representation. ```APIDOC ### Display Implementation Convert to string: ```rust println!("{}", Algorithm::Ed25519); // Outputs: ssh-ed25519 ``` ``` -------------------------------- ### Public Module: KnownHosts Source: https://github.com/rustcrypto/ssh/blob/master/_autodocs/modules-and-exports.md Provides functionality for parsing OpenSSH `known_hosts` files. Requires `alloc` and `std` features. ```APIDOC ## Module: known_hosts (requires `alloc` and `std`) Parser for OpenSSH `known_hosts` files. ### Struct: `KnownHosts` Represents parsed content from a `known_hosts` file. ``` -------------------------------- ### Get PublicKey Algorithm Source: https://github.com/rustcrypto/ssh/blob/master/_autodocs/api-reference/ssh-key-public.md Use PublicKey::algorithm to retrieve the cryptographic algorithm used by the public key. This returns an enum variant representing algorithms like Ed25519, RSA, or ECDSA. ```rust use ssh_key::Algorithm; match key.algorithm() { Algorithm::Ed25519 => println!("Ed25519 key"), Algorithm::Rsa { .. } => println!("RSA key"), _ => println!("Other algorithm"), } ``` -------------------------------- ### Public Module: AuthorizedKeys Source: https://github.com/rustcrypto/ssh/blob/master/_autodocs/modules-and-exports.md Provides functionality for parsing OpenSSH `authorized_keys` files. ```APIDOC ## Module: authorized_keys Parser for OpenSSH `authorized_keys` files. ### Struct: `AuthorizedKeys` Represents parsed content from an `authorized_keys` file. // Parses keys from files ``` -------------------------------- ### Graceful Degradation for SSH Key Support Source: https://github.com/rustcrypto/ssh/blob/master/_autodocs/usage-patterns.md Demonstrates a pattern for gracefully handling different SSH key algorithm types by checking if a key is 'modern' (e.g., Ed25519) or 'legacy'. This allows applications to provide different levels of support or warnings based on the key type. ```rust use ssh_key::{PublicKey, Algorithm}; let key = PublicKey::from_openssh(key_str)?; let is_modern = matches!(key.algorithm(), Algorithm::Ed25519); let support_level = if is_modern { "recommended" } else { "legacy" }; println!("Key support: {}", support_level); ``` -------------------------------- ### Securely Clearing Sensitive Data with Zeroize Source: https://github.com/rustcrypto/ssh/blob/master/_autodocs/usage-patterns.md Demonstrates how to securely handle sensitive data like passwords used for decrypting private keys. Using `Zeroizing` ensures that the memory is automatically cleared when the variable goes out of scope. Manual clearing is also shown. ```rust use ssh_key::PrivateKey; use zeroize::Zeroizing; let password = "my-secret"; let key = PrivateKey::from_openssh(pem_data)?; { let decrypted = key.decrypt(password)?; // Use decrypted key } // When Zeroizing drops, memory is cleared // Manual clearing: let mut pwd = password.to_string(); // Use pwd // pwd.zeroize(); // Requires zeroize feature ``` -------------------------------- ### Algorithm Support Matrix Source: https://github.com/rustcrypto/ssh/blob/master/_autodocs/api-reference/ssh-key-algorithm.md A matrix detailing the support status, required features, and use cases for various SSH key algorithms. ```APIDOC ## Algorithm Support Matrix | Algorithm | Feature | Supported | Use Case | |-----------|---------|-----------|----------| | Ed25519 | `ed25519` | ✅ Default | Modern, recommended | | ECDSA P-256 | `ecdsa` | ✅ | Legacy systems | | ECDSA P-384 | `ecdsa` | ✅ | Legacy systems | | ECDSA P-521 | `ecdsa` | ✅ | Legacy systems | | RSA | `rsa` | ✅ | Legacy systems | | DSA | `alloc` | ⚠️ Deprecated | Legacy only | | SK Ed25519 | `ed25519` | ✅ | FIDO/U2F keys | | SK ECDSA P-256 | `ecdsa` | ✅ | FIDO/U2F keys | ``` -------------------------------- ### Batch Processing SSH Keys Source: https://github.com/rustcrypto/ssh/blob/master/_autodocs/usage-patterns.md Shows how to efficiently process multiple SSH keys from a string by iterating over lines and collecting them into a vector of PublicKeys. Errors during parsing are collected. ```rust use ssh_key::PublicKey; let keys_str = "key1\nkey2\nkey3"; let keys: Result, _> = keys_str .lines() .map(PublicKey::from_openssh) .collect(); for key in keys? { println!("{}", key.fingerprint(ssh_key::HashAlg::Sha256)); } ``` -------------------------------- ### Builder for SSH Certificates Source: https://github.com/rustcrypto/ssh/blob/master/_autodocs/types.md Provides functionality for constructing and signing SSH certificates. Contains implementation details. ```rust pub struct Builder { // Implementation details } ``` -------------------------------- ### Generate and Save Random SSH Key Source: https://github.com/rustcrypto/ssh/blob/master/_autodocs/usage-patterns.md Demonstrates generating a new random SSH private key (e.g., Ed25519) using `OsRng`, optionally encrypting it with a password, and saving it to a file. ```rust use ssh_key::{PrivateKey, Algorithm}; use ssh_key::rand_core::OsRng; let mut rng = OsRng; let key = PrivateKey::random(&mut rng, Algorithm::Ed25519)?; // Encrypt with password let encrypted = key.encrypt(&mut rng, "password")?; // Save encrypted.write_openssh("~/.ssh/id_ed25519")?; ``` -------------------------------- ### Algorithm Display to String Source: https://github.com/rustcrypto/ssh/blob/master/_autodocs/api-reference/ssh-key-algorithm.md Shows how to convert an Algorithm enum variant to its string representation using the Display implementation. ```rust println!("{}", Algorithm::Ed25519); // Outputs: ssh-ed25519 ``` -------------------------------- ### Public Module: Certificate Source: https://github.com/rustcrypto/ssh/blob/master/_autodocs/modules-and-exports.md Provides support for OpenSSH certificate authority operations, including building and managing certificates. ```APIDOC ## Module: certificate (requires `alloc`) OpenSSH certificate authority support. ### Struct: `Certificate` Represents an OpenSSH certificate. ### Struct: `Builder` Used for building and signing certificates. ### Enum: `CertType` Defines the type of certificate (User or Host). #### Variants: - `User` - `Host` ### Struct: `OptionsMap` Represents a map of certificate options and extensions. ### Enum: `Field` Identifiers for certificate fields. ### Submodules: - `builder` — Certificate builder for signing - `cert_type` — Certificate type enum - `field` — Field identifiers - `options_map` — Options/extensions map ``` -------------------------------- ### Certificate Module Structure Source: https://github.com/rustcrypto/ssh/blob/master/_autodocs/modules-and-exports.md Provides structures for OpenSSH certificate management, including `Certificate`, `Builder`, `CertType`, and `OptionsMap`. This module requires the `alloc` feature. ```rust #[cfg(feature = "alloc")] pub mod certificate { pub struct Certificate { /* ... */ } pub struct Builder { /* ... */ } pub enum CertType { User, Host } pub struct OptionsMap { /* ... */ } pub enum Field { /* ... */ } } ``` -------------------------------- ### Full-Featured SSH Dependencies Source: https://github.com/rustcrypto/ssh/blob/master/_autodocs/README.md Configures all available features for SSH crates, enabling a wide range of ciphers, encoding options, and key algorithm support. ```toml [dependencies] ssh-cipher = { version = "0.7", features = ["aes", "tdes", "chacha20poly1305"] } ssh-encoding = { version = "0.2", features = ["alloc", "base64", "pem", "derive", "digest"] } ssh-key = { version = "0.6", features = ["ed25519", "ecdsa", "rsa", "dsa", "encryption", "rand_core", "ppk", "serde", "std"] } ``` -------------------------------- ### Builder Pattern for Certificate Construction Source: https://github.com/rustcrypto/ssh/blob/master/_autodocs/api-reference/ssh-key-certificate.md Construct and sign SSH certificates using the Builder pattern. ```APIDOC ## Builder Pattern Use `Builder` to construct certificates for signing. ```rust pub struct Builder { // Implementation details } ``` ### Builder Methods **new(serial: u64, cert_type: CertType, key_id: String, public_key: PublicKey)** → `Builder` - Create a new certificate builder **principal(mut self, principal: String) -> Self** - Add an authorized principal (user/hostname) **valid_after(mut self, timestamp: u64) -> Self** - Set validity start time **valid_before(mut self, timestamp: u64) -> Self** - Set validity end time **critical_option(mut self, key: String, value: Vec) -> Self** - Add a critical option **extension(mut self, key: String, value: Vec) -> Self** - Add a non-critical extension **sign(self, ca_key: &SigningKey) -> Result** - Sign the certificate with a CA private key ### Example ```rust use ssh_key::certificate::{Builder, CertType}; use ssh_key::PrivateKey; let ca_key = PrivateKey::from_openssh(ca_pem)?; let user_pub_key = PublicKey::from_openssh(user_key_str)?; let cert = Builder::new( 1, CertType::User, "user-key-2024".to_string(), user_pub_key ) .principal("alice".to_string()) .principal("alice@example.com".to_string()) .valid_after(1704067200) // 2024-01-01 .valid_before(1735689600) // 2025-01-01 .sign(&ca_key.signing_key())?; ``` ``` -------------------------------- ### Signature Module Source: https://github.com/rustcrypto/ssh/blob/master/_autodocs/modules-and-exports.md Contains structures for handling SSH signatures, including `Signature` and `SigningKey`, for signing and verifying messages. This module requires the `alloc` feature. ```rust #[cfg(feature = "alloc")] pub mod signature { pub struct Signature { /* ... */ } pub struct SigningKey { /* ... */ } } ``` -------------------------------- ### Sign a message with an SSH private key Source: https://github.com/rustcrypto/ssh/blob/master/_autodocs/api-reference/ssh-key-private.md Use this method to create an SSH signature over a message. The namespace specifies the context of the signing operation, such as 'git'. ```rust use ssh_key::PrivateKey; let key = PrivateKey::from_openssh(pem_data)?; let message = b"data to sign"; let signature = key.sign("example", message)?; ``` -------------------------------- ### Basic PrivateKey Parsing Error Handling Source: https://github.com/rustcrypto/ssh/blob/master/_autodocs/errors.md Demonstrates how to handle potential errors when parsing an OpenSSH private key. It uses a match statement to differentiate between specific errors like 'Encrypted' and general 'Encoding' errors. ```rust use ssh_key::PrivateKey; match PrivateKey::from_openssh(pem_data) { Ok(key) => println!("Loaded key"), Err(ssh_key::Error::Encrypted) => println!("Key is encrypted"), Err(ssh_key::Error::Encoding(e)) => println!("Parse error: {e}"), Err(e) => println!("Error: {e}"), } ``` -------------------------------- ### Create and Sign an SSH Certificate Source: https://github.com/rustcrypto/ssh/blob/master/_autodocs/usage-patterns.md Creates a new SSH certificate signed by a CA private key. This involves specifying certificate details like serial number, type, principals, and validity periods. ```rust use ssh_key::{ PrivateKey, PublicKey, certificate::{Builder, CertType}, }; let ca_key = PrivateKey::from_openssh(ca_pem)?; let user_pub_key = PublicKey::from_openssh(user_key_str)?; let cert = Builder::new( 1, // serial CertType::User, "user-key-2024-01".to_string(), user_pub_key ) .principal("alice".to_string()) .principal("alice@company.com".to_string()) .valid_after(1704067200) // 2024-01-01 00:00:00 UTC .valid_before(1735689600) // 2025-01-01 00:00:00 UTC .sign(&ca_key.signing_key())?; let cert_str = cert.to_openssh()?; println!("{}", cert_str); ``` -------------------------------- ### Sign a Message with Private Key Source: https://github.com/rustcrypto/ssh/blob/master/_autodocs/usage-patterns.md Signs a message using a private key. The `namespace` parameter specifies the context of the signature, and the message is provided as a byte slice. ```rust use ssh_key::PrivateKey; let key = PrivateKey::from_openssh(pem_data)?; let message = b"data to sign"; let signature = key.sign("git", message)?; // Export signature let sig_str = signature.to_openssh()?; ``` -------------------------------- ### Caching Fingerprints for Performance Source: https://github.com/rustcrypto/ssh/blob/master/_autodocs/usage-patterns.md Demonstrates caching a computed fingerprint to avoid redundant calculations, which can improve performance when the same key's fingerprint is needed multiple times. ```rust use ssh_key::{PublicKey, HashAlg}; let key = PublicKey::from_openssh(key_str)?; // Cache fingerprint let fp = key.fingerprint(HashAlg::Sha256); // Use cached value multiple times for _ in 0..1000 { // Use fp instead of recomputing } ``` -------------------------------- ### Encrypt Private Key Source: https://github.com/rustcrypto/ssh/blob/master/_autodocs/api-reference/ssh-key-private.md Use `PrivateKey::encrypt` to encrypt an unencrypted private key with a password. This method requires a cryptographically secure RNG and the `encryption` feature. ```rust use ssh_key::PrivateKey; use ssh_key::rand_core::OsRng; let key = PrivateKey::random(&mut OsRng, Algorithm::Ed25519)?; let encrypted = key.encrypt(&mut OsRng, "my-secure-password")?; ``` -------------------------------- ### Public Module: PrivateKey Source: https://github.com/rustcrypto/ssh/blob/master/_autodocs/modules-and-exports.md Handles SSH private key parsing, decryption, and signing. Supports various key pair types. ```APIDOC ## Module: private SSH private key parsing, decryption, and signing. ### Struct: `PrivateKey` Represents an SSH private key. ### Enum: `KeypairData` Represents the different types of key pair data. #### Variants: - `Ed25519(Ed25519Keypair)` - `#[cfg(feature = "ecdsa")] Ecdsa(EcdsaKeypair)` - `// ... other keypair types` ### Struct: `Ed25519Keypair` Represents an Ed25519 keypair. ### Submodules: - `ed25519` — Ed25519 keypair (default) - `ecdsa` — ECDSA keypair (requires `ecdsa`) - `rsa` — RSA keypair (requires `rsa`, `alloc`) - `dsa` — DSA keypair (requires `alloc`) - `sk` — FIDO/U2F keypair - `keypair` — KeypairData enum - `opaque` — Opaque keypair for unknown algorithms ``` -------------------------------- ### Pattern Match SSH Key Error Types Source: https://github.com/rustcrypto/ssh/blob/master/_autodocs/usage-patterns.md Illustrates how to handle potential errors when loading or decrypting SSH keys by pattern matching on specific `ssh_key::Error` variants. This allows for granular error handling, such as distinguishing wrong passwords from general parsing issues. ```rust use ssh_key::{PrivateKey, Error}; match PrivateKey::from_openssh(pem_data) { Ok(key) => { if key.is_encrypted() { match key.decrypt("password") { Ok(decrypted) => println!("Decrypted"), Err(Error::Crypto) => println!("Wrong password"), Err(e) => println!("Error: {}", e), } } } Err(Error::Encoding(e)) => println!("Parse error: {}", e), Err(Error::Version { number }) => println!("Unsupported format version: {}", number), Err(e) => println!("Error: {}", e), } ``` -------------------------------- ### Checking and Decrypting Encrypted Private Keys Source: https://github.com/rustcrypto/ssh/blob/master/_autodocs/errors.md Shows how to check if a private key is encrypted and then decrypt it using a password. This pattern is useful when dealing with keys that may or may not require a passphrase. ```rust use ssh_key::PrivateKey; let key = PrivateKey::from_openssh(pem_data)?; if key.is_encrypted() { // Need password to decrypt let decrypted = key.decrypt("password") .map_err(|e| println!("Wrong password: {}", e))?; } else { // Can use directly } ``` -------------------------------- ### Read Certificate from File Source: https://github.com/rustcrypto/ssh/blob/master/_autodocs/api-reference/ssh-key-certificate.md Reads and parses a certificate from a file path. Requires the `std` feature to be enabled. This is a convenient method for loading certificates stored on the filesystem. ```rust #[cfg(feature = "std")] pub fn read_file(path: &Path) -> Result ``` -------------------------------- ### Handle Feature-Dependent SSH Key Errors Source: https://github.com/rustcrypto/ssh/blob/master/_autodocs/usage-patterns.md Shows how to conditionally compile code for specific SSH key algorithms (like RSA) based on Cargo features. This allows for building a minimal binary that only includes support for necessary algorithms, with fallback error messages for unsupported features. ```rust use ssh_key::PrivateKey; let key = PrivateKey::from_openssh(pem_data)?; match key.algorithm() { ssh_key::Algorithm::Rsa { .. } => { #[cfg(feature = "rsa")] { // Can sign with RSA let sig = key.sign("namespace", message)?; } #[cfg(not(feature = "rsa"))] { eprintln!("RSA support not enabled"); } } _ => {} ``` -------------------------------- ### Write Certificate to File Source: https://github.com/rustcrypto/ssh/blob/master/_autodocs/api-reference/ssh-key-certificate.md Writes the Certificate object to a file at the specified path. Requires the `std` feature. This method serializes the certificate to its binary form before writing. Returns an error if the write operation fails. ```rust #[cfg(feature = "std")] pub fn write_file(&self, path: &Path) -> Result<()> ``` -------------------------------- ### FromStr Implementation for Algorithm Source: https://github.com/rustcrypto/ssh/blob/master/_autodocs/api-reference/ssh-key-algorithm.md Allows parsing an SSH algorithm directly from its string representation. ```APIDOC ### FromStr Implementation Parse algorithm from string: ```rust use std::str::FromStr; use ssh_key::Algorithm; let alg = Algorithm::from_str("ssh-ed25519")?; ``` ``` -------------------------------- ### Serialize Certificate to OpenSSH Format Source: https://github.com/rustcrypto/ssh/blob/master/_autodocs/api-reference/ssh-key-certificate.md Encodes the current Certificate object into an OpenSSH-formatted string. This is the inverse of `from_openssh` and is useful for generating certificates in a standard text format. Returns an error if encoding fails. ```rust pub fn to_openssh(&self) -> Result ``` -------------------------------- ### AlgorithmName Struct Definition (alloc feature) Source: https://github.com/rustcrypto/ssh/blob/master/_autodocs/api-reference/ssh-key-algorithm.md Represents unknown or custom algorithm names, used for Algorithm::Other to denote non-standard algorithms. Requires the 'alloc' feature. ```rust #[cfg(feature = "alloc")] pub struct AlgorithmName { // Implementation details } ``` -------------------------------- ### Generate Random Private Key Source: https://github.com/rustcrypto/ssh/blob/master/_autodocs/api-reference/ssh-key-private.md Use `PrivateKey::random` to generate a new random private key for a specified algorithm. This requires a cryptographically secure random number generator and the `rand_core` feature. ```rust use ssh_key::{Algorithm, PrivateKey}; use ssh_key::rand_core::OsRng; let mut rng = OsRng; let key = PrivateKey::random(&mut rng, Algorithm::Ed25519)?; ``` -------------------------------- ### Create Stateful Encryptor Source: https://github.com/rustcrypto/ssh/blob/master/_autodocs/api-reference/ssh-cipher.md Creates a stateful encryptor for block cipher modes like CBC or CTR. This is not applicable to AEAD modes. ```rust #[cfg(any(feature = "aes", feature = "tdes"))] pub fn encryptor(self, key: &[u8], iv: &[u8]) -> Result> where C: BlockCipher ``` -------------------------------- ### SSH Derive Macros for Encode and Decode Source: https://github.com/rustcrypto/ssh/blob/master/_autodocs/modules-and-exports.md Procedural macros for deriving Encode and Decode traits for SSH data structures. ```rust #[proc_macro_derive(Decode, attributes(ssh))] pub fn derive_decode(input: TokenStream) -> TokenStream { /* ... */ } #[proc_macro_derive(Encode, attributes(ssh))] pub fn derive_encode(input: TokenStream) -> TokenStream { /* ... */ } ```