### Set up TLS Server with PKCS#12 Identity Source: https://context7.com/kornelski/rust-security-framework/llms.txt Implement a TLS server using `ServerBuilder`. This example demonstrates loading a server identity from a PKCS#12 file and handling incoming TLS connections, including reading requests and sending responses. ```rust use security_framework::secure_transport::ServerBuilder; use std::io::{Read, Write}; use std::net::TcpListener; use std::thread; fn run_tls_server(pkcs12_der: &[u8], password: &str) { let builder = ServerBuilder::from_pkcs12(pkcs12_der, password) .expect("failed to parse PKCS#12"); let listener = TcpListener::bind("0.0.0.0:8443").unwrap(); for tcp_stream in listener.incoming() { let tcp_stream = tcp_stream.unwrap(); let builder_clone = builder.clone(); thread::spawn(move || { let mut tls = builder_clone.handshake(tcp_stream) .expect("TLS handshake failed"); let mut req = vec![0u8; 4096]; let n = tls.read(&mut req).unwrap(); println!("Received: {}", String::from_utf8_lossy(&req[..n])); tls.write_all(b"HTTP/1.0 200 OK\r\n\r\nHello TLS").unwrap(); }); } } ``` -------------------------------- ### Search Keychain Certificates with ItemSearchOptions Source: https://context7.com/kornelski/rust-security-framework/llms.txt Use `ItemSearchOptions` to build fine-grained searches for certificates in the keychain. This example demonstrates how to find all trusted certificates and load their references and attributes. ```rust use security_framework::item::{ItemClass, ItemSearchOptions, Limit, SearchResult, Reference}; fn search_keychain_certificates() { // Find all trusted certificates in the keychain let results = ItemSearchOptions::new() .class(ItemClass::certificate()) .load_refs(true) // return SecCertificate references .load_attributes(true) .limit(Limit::All) .trusted_only(Some(true)) .search() .expect("keychain search failed"); for result in &results { match result { SearchResult::Ref(Reference::Certificate(cert)) => { println!("Subject: {}", cert.subject_summary()); } SearchResult::Dict(dict) => { // Simplify attributes dict to HashMap if let Some(attrs) = SearchResult::Dict(dict.clone()).simplify_dict() { println!("Attrs: {:?}", attrs.get("labl")); } } _ => {} } } } ``` -------------------------------- ### Establish TLS Client Connection with Default System Trust Source: https://context7.com/kornelski/rust-security-framework/llms.txt Use `ClientBuilder` to initiate a TLS client connection over any `Read + Write` stream. This example demonstrates a simple HTTPS connection to google.com using default system trust anchors. ```rust use security_framework::secure_transport::ClientBuilder; use std::io::{Read, Write}; use std::net::TcpStream; fn main() { // Simple HTTPS connection with default system trust let stream = TcpStream::connect("google.com:443").unwrap(); let mut tls = ClientBuilder::new() .handshake("google.com", stream) .unwrap(); println!("Cipher: {:?}", tls.context().negotiated_cipher().unwrap()); println!("Protocol: {:?}", tls.context().negotiated_protocol_version().unwrap()); tls.write_all(b"GET / HTTP/1.0\r\nHost: google.com\r\n\r\n").unwrap(); tls.flush().unwrap(); let mut body = Vec::new(); tls.read_to_end(&mut body).unwrap(); println!("{}", String::from_utf8_lossy(&body)); } ``` -------------------------------- ### Add Generic Password Item with ItemAddOptions Source: https://context7.com/kornelski/rust-security-framework/llms.txt Use `ItemAddOptions` to add generic password items to the keychain. This example shows how to set the password data, label, service, and account name, with an option for Data Protection Keychain on supported platforms. ```rust use core_foundation::data::CFData; use security_framework::item::{ItemAddOptions, ItemAddValue, ItemClass, Location}; fn add_generic_password_item() { let password_data = CFData::from_buffer(b"my-api-key-12345"); let mut opts = ItemAddOptions::new(ItemAddValue::Data { class: ItemClass::generic_password(), data: password_data, }); opts.set_label("My API Key") .set_service("com.example.api") .set_account_name("service-account"); #[cfg(any(feature = "OSX_10_15", not(target_os = "macos")))] opts.set_location(Location::DataProtectionKeychain); opts.add().expect("failed to add keychain item"); println!("Item added to keychain."); } ``` -------------------------------- ### ServerBuilder - TLS server handshake Source: https://context7.com/kornelski/rust-security-framework/llms.txt Shows how to set up a TLS server using ServerBuilder, load a server identity from a PKCS#12 file, and handle incoming TLS connections. ```APIDOC ## ServerBuilder - TLS server handshake `ServerBuilder` wraps a `SecIdentity` (certificate + private key) and optional certificate chain to accept incoming TLS connections on the server side. The identity is typically loaded from a PKCS#12 file. ### Description This example demonstrates how to create a TLS server that listens for incoming connections on a specified port. It loads the server's identity (certificate and private key) from a PKCS#12 file and handles client handshakes and basic request/response. ### Method `ServerBuilder::from_pkcs12(pkcs12_der, password).handshake(tcp_stream)` ### Parameters - **pkcs12_der**: `&[u8]` - The DER-encoded PKCS#12 data. - **password**: `&str` - The password for the PKCS#12 file. - **tcp_stream**: `impl Read + Write` - The incoming TCP stream to wrap with TLS. ### Request Example ```rust use security_framework::secure_transport::ServerBuilder; use std::io::{Read, Write}; use std::net::TcpListener; use std::thread; fn run_tls_server(pkcs12_der: &[u8], password: &str) { let builder = ServerBuilder::from_pkcs12(pkcs12_der, password) .expect("failed to parse PKCS#12"); let listener = TcpListener::bind("0.0.0.0:8443").unwrap(); for tcp_stream in listener.incoming() { let tcp_stream = tcp_stream.unwrap(); let builder_clone = builder.clone(); thread::spawn(move || { let mut tls = builder_clone.handshake(tcp_stream) .expect("TLS handshake failed"); let mut req = vec![0u8; 4096]; let n = tls.read(&mut req).unwrap(); println!("Received: {}", String::from_utf8_lossy(&req[..n])); tls.write_all(b"HTTP/1.0 200 OK\r\n\r\nHello TLS").unwrap(); }); } } ``` ### Response #### Success Response Handles incoming TLS connections, reads client requests, and sends a simple HTTP response. The `handshake` method returns a `TlsStream` for further communication. #### Response Example ``` Received: GET / HTTP/1.0 Host: localhost:8443 User-Agent: curl/7.64.1 Accept: */* ``` ``` -------------------------------- ### ClientBuilder - TLS client handshake Source: https://context7.com/kornelski/rust-security-framework/llms.txt Demonstrates how to establish a basic TLS client connection using ClientBuilder, including connecting to a server and performing a handshake. ```APIDOC ## ClientBuilder - TLS client handshake `ClientBuilder` is the high-level entry point for establishing a TLS client connection over any `Read + Write` stream. It exposes a fluent builder for configuring certificates, cipher suites, protocol versions, ALPN, SNI, and session tickets before calling `handshake`. ### Description This example shows a simple HTTPS connection with default system trust. It connects to a specified host and port, performs a TLS handshake, and then prints the negotiated cipher and protocol version. ### Method `ClientBuilder::new().handshake(hostname, stream)` ### Parameters - **hostname**: `&str` - The hostname to connect to. - **stream**: `impl Read + Write` - The underlying stream to use for the connection. ### Request Example ```rust use security_framework::secure_transport::ClientBuilder; use std::io::{Read, Write}; use std::net::TcpStream; fn main() { // Simple HTTPS connection with default system trust let stream = TcpStream::connect("google.com:443").unwrap(); let mut tls = ClientBuilder::new() .handshake("google.com", stream) .unwrap(); println!("Cipher: {:?}", tls.context().negotiated_cipher().unwrap()); println!("Protocol: {:?}", tls.context().negotiated_protocol_version().unwrap()); tls.write_all(b"GET / HTTP/1.0\r\nHost: google.com\r\n\r\n").unwrap(); tls.flush().unwrap(); let mut body = Vec::new(); tls.read_to_end(&mut body).unwrap(); println!("{}", String::from_utf8_lossy(&body)); } ``` ### Response #### Success Response Returns a `TlsStream` object representing the established TLS connection, allowing for reading and writing encrypted data. #### Response Example ``` Cipher: Some(TlsCipher { version: TlsVersion::V1_3, name: "TLS_AES_256_GCM_SHA384" }) Protocol: Some(TlsVersion::V1_3) ... ``` ``` -------------------------------- ### Sign, Verify, Encrypt, and Decrypt with SecKey Source: https://context7.com/kornelski/rust-security-framework/llms.txt Demonstrates generating EC and RSA key pairs, signing data with an EC key, verifying the signature, and encrypting/decrypting data with an RSA key. Supports various algorithms like ECDSA and RSA-OAEP. ```rust use security_framework::key::{GenerateKeyOptions, KeyType, SecKey, Token}; use security_framework_sys::key::Algorithm; fn sign_and_verify_with_ec_key() { // Generate an EC key pair (P-256) in software let private_key = SecKey::new( GenerateKeyOptions::default() .set_key_type(KeyType::ec_sec_prime_random()) .set_size_in_bits(256) .set_label("My Signing Key"), ).expect("key generation failed"); let public_key = private_key.public_key().expect("no public key"); let message = b"hello, world"; let algorithm = Algorithm::ECDSASignatureMessageX962SHA256; // Sign let signature = private_key .create_signature(algorithm, message) .expect("signing failed"); println!("Signature length: {} bytes", signature.len()); // Verify let valid = public_key .verify_signature(algorithm, message, &signature) .expect("verification error"); assert!(valid, "signature should be valid"); // Encrypt / decrypt with RSA let rsa_key = SecKey::new( GenerateKeyOptions::default() .set_key_type(KeyType::rsa()) .set_size_in_bits(2048), ).unwrap(); let rsa_pub = rsa_key.public_key().unwrap(); let ciphertext = rsa_pub .encrypt_data(Algorithm::RSAEncryptionOAEPSHA256, b"secret payload") .unwrap(); let plaintext = rsa_key .decrypt_data(Algorithm::RSAEncryptionOAEPSHA256, &ciphertext) .unwrap(); assert_eq!(plaintext, b"secret payload"); } ``` -------------------------------- ### ClientBuilder - custom anchor certificates and ALPN Source: https://context7.com/kornelski/rust-security-framework/llms.txt Illustrates advanced TLS client configuration with custom anchor certificates, restricted trust anchors, minimum/maximum protocol versions, and Application-Layer Protocol Negotiation (ALPN). ```APIDOC ## ClientBuilder - custom anchor certificates and ALPN `ClientBuilder` allows specifying custom root certificates, restricting accepted TLS versions, and configuring ALPN protocol negotiation for advanced use cases such as mutual TLS or HTTP/2. ### Description This example demonstrates how to configure a TLS client to use custom CA certificates, enforce specific TLS protocol versions (TLS 1.2 and 1.3), and negotiate application protocols like HTTP/2 or HTTP/1.1. ### Method `ClientBuilder::new().anchor_certificates(certs).trust_anchor_certificates_only(bool).protocol_min(SslProtocol).protocol_max(SslProtocol).alpn_protocols(protocols).handshake(hostname, stream)` ### Parameters - **anchor_certificates**: `&[SecCertificate]` - A slice of custom root certificates to trust. - **trust_anchor_certificates_only**: `bool` - If true, only the provided anchor certificates are trusted, excluding system roots. - **protocol_min**: `SslProtocol` - The minimum TLS protocol version to use. - **protocol_max**: `SslProtocol` - The maximum TLS protocol version to use. - **alpn_protocols**: `&[&str]` - A slice of strings representing the ALPN protocols to negotiate. - **hostname**: `&str` - The hostname to connect to. - **stream**: `impl Read + Write` - The underlying stream to use for the connection. ### Request Example ```rust use security_framework::certificate::SecCertificate; use security_framework::secure_transport::{ClientBuilder, SslProtocol}; use std::net::TcpStream; fn connect_with_custom_ca(ca_der: &[u8]) { let ca_cert = SecCertificate::from_der(ca_der).expect("invalid DER"); let stream = TcpStream::connect("my_server.example.com:443").unwrap(); let mut tls = ClientBuilder::new() .anchor_certificates(&[ca_cert]) .trust_anchor_certificates_only(true) // reject system roots .protocol_min(SslProtocol::TLS12) // require TLS 1.2+ .protocol_max(SslProtocol::TLS13) .alpn_protocols(&["h2", "http/1.1"]) // negotiate HTTP/2 or HTTP/1.1 .handshake("my_server.example.com", stream) .expect("TLS handshake failed"); println!( "ALPN agreed: {:?}", tls.context().alpn_protocols().unwrap() ); } ``` ### Response #### Success Response Returns a `TlsStream` object representing the established TLS connection with custom configurations applied. The ALPN negotiated protocol is accessible via `tls.context().alpn_protocols()`. #### Response Example ``` ALPN agreed: Some(["h2"]) ``` ``` -------------------------------- ### Pkcs12ImportOptions — import PKCS#12 identity bundles Source: https://context7.com/kornelski/rust-security-framework/llms.txt Imports a PKCS#12 (.p12) file containing a certificate and private key as a `SecIdentity`. This is required by `ServerBuilder` and `SslContext::set_certificate`. ```APIDOC ## `Pkcs12ImportOptions` — import PKCS#12 identity bundles `Pkcs12ImportOptions` imports a PKCS#12 (`.p12`) file containing a certificate and private key as a `SecIdentity`, which is required by `ServerBuilder` and `SslContext::set_certificate`. ```rust use security_framework::import_export::Pkcs12ImportOptions; fn load_server_identity(p12_bytes: &[u8], passphrase: &str) { let identities = Pkcs12ImportOptions::new() .passphrase(passphrase) .import(p12_bytes) .expect("failed to import PKCS#12"); for id in &identities { println!("Label: {:?}", id.label); if let Some(cert_chain) = &id.cert_chain { for cert in cert_chain { println!(" Chain cert: {}", cert.subject_summary()); } } if let Some(identity) = &id.identity { println!("Identity loaded: {:?}", identity); } } } ``` ``` -------------------------------- ### GenerateKeyOptions — Secure Enclave key generation Source: https://context7.com/kornelski/rust-security-framework/llms.txt Configures key creation, including storage in the Secure Enclave with an access control policy. This allows for keys that are inaccessible to the host CPU. ```APIDOC ## `GenerateKeyOptions` — Secure Enclave key generation `GenerateKeyOptions` configures key creation including storage in the Secure Enclave (unavailable to the host CPU) with an access control policy. ```rust use security_framework::access_control::SecAccessControl; use security_framework::item::Location; use security_framework::key::{GenerateKeyOptions, KeyType, SecKey, Token}; fn generate_secure_enclave_key() { // Access control: require biometry to use the key let access = SecAccessControl::create_with_flags( security_framework_sys::access_control::kSecAttrAccessibleWhenUnlockedThisDeviceOnly, security_framework_sys::access_control::SecAccessControlCreateFlags::BIOMETRY_ANY, ).expect("access control creation failed"); let key = SecKey::new( GenerateKeyOptions::default() .set_key_type(KeyType::ec_sec_prime_random()) .set_size_in_bits(256) .set_token(Token::SecureEnclave) .set_label("Biometric Signing Key") .set_access_control(access), ).expect("Secure Enclave key generation failed"); println!("Secure Enclave key: {:?}", key); // The private key is NOT exportable from the Secure Enclave assert!(key.external_representation().is_none()); } ``` ``` -------------------------------- ### Low-Level TLS Context Configuration Source: https://context7.com/kornelski/rust-security-framework/llms.txt Configure granular TLS settings like cipher suites, protocol versions, SNI, and ALPN using `SslContext`. Requires `TcpStream` for connection. ```rust use security_framework::secure_transport::{ SslConnectionType, SslContext, SslProtocol, SslProtocolSide, }; use std::net::TcpStream; fn low_level_tls_connect() { let mut ctx = SslContext::new(SslProtocolSide::CLIENT, SslConnectionType::STREAM).unwrap(); // Set the expected server hostname (used for SNI and cert validation) ctx.set_peer_domain_name("google.com").unwrap(); // Restrict to TLS 1.2 and TLS 1.3 only ctx.set_protocol_version_min(SslProtocol::TLS12).unwrap(); ctx.set_protocol_version_max(SslProtocol::TLS13).unwrap(); // Enable session tickets for resumption (pair with set_peer_id) ctx.set_peer_id(b"session-key-google").unwrap(); ctx.set_session_tickets_enabled(true).unwrap(); // Negotiate HTTP/2 via ALPN ctx.set_alpn_protocols(&["h2"]).unwrap(); let stream = TcpStream::connect("google.com:443").unwrap(); let tls = ctx.handshake(stream).unwrap(); println!("ALPN: {:?}", tls.context().alpn_protocols().unwrap()); println!("Cipher: {:?}", tls.context().negotiated_cipher().unwrap()); } ``` -------------------------------- ### Import PKCS#12 Identity Bundle Source: https://context7.com/kornelski/rust-security-framework/llms.txt Imports a PKCS#12 (.p12) file containing a certificate and private key into a SecIdentity. Requires the passphrase for decryption. ```rust use security_framework::import_export::Pkcs12ImportOptions; fn load_server_identity(p12_bytes: &[u8], passphrase: &str) { let identities = Pkcs12ImportOptions::new() .passphrase(passphrase) .import(p12_bytes) .expect("failed to import PKCS#12"); for id in &identities { println!("Label: {:?}", id.label); if let Some(cert_chain) = &id.cert_chain { for cert in cert_chain { println!(" Chain cert: {}", cert.subject_summary()); } } if let Some(identity) = &id.identity { println!("Identity loaded: {:?}", identity); } } } ``` -------------------------------- ### Configure TLS Client with Custom CA and ALPN Source: https://context7.com/kornelski/rust-security-framework/llms.txt Advanced TLS client configuration using `ClientBuilder`. This snippet shows how to specify custom root certificates, enforce minimum/maximum TLS versions, and negotiate Application-Layer Protocol Negotiation (ALPN) protocols. ```rust use security_framework::certificate::SecCertificate; use security_framework::secure_transport::{ClientBuilder, SslProtocol}; use std::net::TcpStream; fn connect_with_custom_ca(ca_der: &[u8]) { let ca_cert = SecCertificate::from_der(ca_der).expect("invalid DER"); let stream = TcpStream::connect("my_server.example.com:443").unwrap(); let mut tls = ClientBuilder::new() .anchor_certificates(&[ca_cert]) .trust_anchor_certificates_only(true) // reject system roots .protocol_min(SslProtocol::TLS12) // require TLS 1.2+ .protocol_max(SslProtocol::TLS13) .alpn_protocols(&["h2", "http/1.1"]) // negotiate HTTP/2 or HTTP/1.1 .handshake("my_server.example.com", stream) .expect("TLS handshake failed"); println!( "ALPN agreed: {:?}", tls.context().alpn_protocols().unwrap() ); } ``` -------------------------------- ### `SslContext` - Low-level TLS Context Source: https://context7.com/kornelski/rust-security-framework/llms.txt Demonstrates the usage of `SslContext` for fine-grained control over TLS connections, including setting peer domain name, protocol versions, session tickets, and ALPN. ```APIDOC ## `SslContext` — low-level TLS context `SslContext` is the underlying type behind both `ClientBuilder` and `ServerBuilder`. It exposes granular control over cipher suites, protocol versions, peer identity, session resumption via session tickets, ALPN, and the manual handshake loop. ```rust use security_framework::secure_transport::{ SslConnectionType, SslContext, SslProtocol, SslProtocolSide, }; use std::net::TcpStream; fn low_level_tls_connect() { let mut ctx = SslContext::new(SslProtocolSide::CLIENT, SslConnectionType::STREAM).unwrap(); // Set the expected server hostname (used for SNI and cert validation) ctx.set_peer_domain_name("google.com").unwrap(); // Restrict to TLS 1.2 and TLS 1.3 only ctx.set_protocol_version_min(SslProtocol::TLS12).unwrap(); ctx.set_protocol_version_max(SslProtocol::TLS13).unwrap(); // Enable session tickets for resumption (pair with set_peer_id) ctx.set_peer_id(b"session-key-google").unwrap(); ctx.set_session_tickets_enabled(true).unwrap(); // Negotiate HTTP/2 via ALPN ctx.set_alpn_protocols(&["h2"]).unwrap(); let stream = TcpStream::connect("google.com:443").unwrap(); let tls = ctx.handshake(stream).unwrap(); println!("ALPN: {:?}", tls.context().alpn_protocols().unwrap()); println!("Cipher: {:?}", tls.context().negotiated_cipher().unwrap()); } ``` ``` -------------------------------- ### ItemAddOptions - Add Items to Keychain Source: https://context7.com/kornelski/rust-security-framework/llms.txt Utilize `ItemAddOptions` to add various item types, including passwords, certificates, and keys, to the keychain. You can specify attributes such as label, service, account, and access group. ```APIDOC ## `ItemAddOptions` — add items to the keychain `ItemAddOptions` wraps `SecItemAdd` and supports adding passwords, certificates, keys, and identities to the keychain with attributes like label, service, account, and access group. ### Example Usage: ```rust use core_foundation::data::CFData; use security_framework::item::{ItemAddOptions, ItemAddValue, ItemClass, Location}; fn add_generic_password_item() { let password_data = CFData::from_buffer(b"my-api-key-12345"); let mut opts = ItemAddOptions::new(ItemAddValue::Data { class: ItemClass::generic_password(), data: password_data, }); opts.set_label("My API Key") .set_service("com.example.api") .set_account_name("service-account"); #[cfg(any(feature = "OSX_10_15", not(target_os = "macos")))] opts.set_location(Location::DataProtectionKeychain); opts.add().expect("failed to add keychain item"); println!("Item added to keychain."); } ``` ``` -------------------------------- ### ItemSearchOptions - Search Keychain Items Source: https://context7.com/kornelski/rust-security-framework/llms.txt Use `ItemSearchOptions` to build fine-grained searches for keychain items like certificates, keys, and passwords. You can filter by label, service, account, cloud-sync status, and more. ```APIDOC ## `ItemSearchOptions` — keychain item search `ItemSearchOptions` is a builder for `SecItemCopyMatching`, allowing fine-grained searches across the keychain for certificates, keys, identities, and passwords, with support for label, service, account, cloud-sync status, public key hash, and more. ### Example Usage: ```rust use security_framework::item::{ItemClass, ItemSearchOptions, Limit, SearchResult, Reference}; fn search_keychain_certificates() { // Find all trusted certificates in the keychain let results = ItemSearchOptions::new() .class(ItemClass::certificate()) .load_refs(true) // return SecCertificate references .load_attributes(true) .limit(Limit::All) .trusted_only(Some(true)) .search() .expect("keychain search failed"); for result in &results { match result { SearchResult::Ref(Reference::Certificate(cert)) => { println!("Subject: {}", cert.subject_summary()); } SearchResult::Dict(dict) => { // Simplify attributes dict to HashMap if let Some(attrs) = SearchResult::Dict(dict.clone()).simplify_dict() { println!("Attrs: {:?}", attrs.get("labl")); } } _ => {} } } } ``` ``` -------------------------------- ### Inspect Certificate Details with SecCertificate Source: https://context7.com/kornelski/rust-security-framework/llms.txt Parse and inspect DER-encoded X.509 certificates using `SecCertificate`. This function demonstrates extracting subject and issuer details, serial number, and public key information for certificate pinning. ```rust use security_framework::certificate::SecCertificate; fn inspect_certificate(der_bytes: &[u8]) { let cert = SecCertificate::from_der(der_bytes).expect("invalid DER certificate"); println!("Subject summary: {}", cert.subject_summary()); // DER-encoded X.509 distinguished name let issuer_der = cert.issuer(); println!("Issuer DER length: {} bytes", issuer_der.len()); let subject_der = cert.subject(); println!("Subject DER length: {} bytes", subject_der.len()); // Serial number (returns CFError on failure) match cert.serial_number_bytes() { Ok(serial) => println!("Serial: {}", hex::encode(&serial)), Err(e) => eprintln!("Serial error: {:?}", e), } // SubjectPublicKeyInfo DER for certificate pinning if let Ok(Some(spki)) = cert.public_key_info_der() { println!("SPKI DER ({} bytes) for pinning", spki.len()); } // Round-trip back to DER let re_encoded = cert.to_der(); assert_eq!(der_bytes, re_encoded.as_slice()); } ``` -------------------------------- ### `set_internet_password` / `get_internet_password` / `delete_internet_password` Source: https://context7.com/kornelski/rust-security-framework/llms.txt Manages internet password entries in the system Keychain, associating credentials with server, protocol, authentication type, path, and port. ```APIDOC ## `set_internet_password` / `get_internet_password` / `delete_internet_password` Internet password entries associate credentials with a specific server, protocol, authentication type, path, and port. They mirror the "internet password" class in the system Keychain. ```rust use security_framework::passwords::{ delete_internet_password, get_internet_password, set_internet_password, }; use security_framework_sys::keychain::{SecAuthenticationType, SecProtocolType}; fn internet_password_example() { let server = "api.example.com"; let account = "bob"; let path = "/api/v1"; let port = Some(443u16); set_internet_password( server, None, // security domain (optional) account, path, port, SecProtocolType::HTTPS, SecAuthenticationType::HTMLForm, b"s3cr3t-token", ).expect("could not store internet password"); let pw = get_internet_password( server, None, account, path, port, SecProtocolType::HTTPS, SecAuthenticationType::HTMLForm, ).expect("internet password not found"); println!("Token: {}", String::from_utf8_lossy(&pw)); delete_internet_password( server, None, account, path, port, SecProtocolType::HTTPS, SecAuthenticationType::HTMLForm, ).unwrap(); } ``` ``` -------------------------------- ### Generic Keychain Password CRUD Operations Source: https://context7.com/kornelski/rust-security-framework/llms.txt Perform Create, Read, Update, and Delete operations on generic password entries in the system Keychain using service and account names. Works on macOS and iOS. ```rust use security_framework::passwords::{ delete_generic_password, get_generic_password, set_generic_password, }; fn keychain_generic_password_roundtrip() { let service = "com.example.myapp"; let account = "alice@example.com"; let secret = b"hunter2"; // Store (creates or updates the entry) set_generic_password(service, account, secret) .expect("failed to set password"); // Retrieve let retrieved = get_generic_password(service, account) .expect("password not found"); assert_eq!(retrieved, secret); println!("Retrieved: {}", String::from_utf8_lossy(&retrieved)); // Update — just call set again; it upserts automatically set_generic_password(service, account, b"new-secret").unwrap(); // Delete delete_generic_password(service, account) .expect("failed to delete password"); // Confirm deletion assert!(get_generic_password(service, account).is_err()); } ``` -------------------------------- ### update_item — update existing keychain items Source: https://context7.com/kornelski/rust-security-framework/llms.txt Wraps `SecItemUpdate`, allowing atomic in-place changes to keychain entries found via `ItemSearchOptions` and updated via `ItemUpdateOptions`. ```APIDOC ## `update_item` — update existing keychain items `update_item` wraps `SecItemUpdate`, allowing atomic in-place changes to keychain entries found via `ItemSearchOptions` and updated via `ItemUpdateOptions`. ```rust use core_foundation::data::CFData; use security_framework::item::{ update_item, ItemClass, ItemSearchOptions, ItemUpdateOptions, ItemUpdateValue, }; fn rotate_password(service: &str, account: &str, new_password: &[u8]) { let search = { let mut s = ItemSearchOptions::new(); s.class(ItemClass::generic_password()) .service(service) .account(account); s }; let update = { let mut u = ItemUpdateOptions::new(); u.set_value(ItemUpdateValue::Data(CFData::from_buffer(new_password))); u }; update_item(&search, &update).expect("failed to update keychain item"); println!("Password rotated for {account}@{service}"); } ``` ``` -------------------------------- ### SecCertificate - Parse and Inspect Certificates Source: https://context7.com/kornelski/rust-security-framework/llms.txt The `SecCertificate` struct provides functionality for parsing and inspecting X.509 certificates. It allows extraction of DER encoding, subject/issuer information, email addresses, serial numbers, and public keys. ```APIDOC ## `SecCertificate` — certificate parsing and inspection `SecCertificate` wraps Apple's `SecCertificateRef` and exposes DER encoding/decoding, subject/issuer extraction, email address lookup, serial number retrieval, public key extraction, and certificate pinning via `public_key_info_der`. ### Example Usage: ```rust use security_framework::certificate::SecCertificate; fn inspect_certificate(der_bytes: &[u8]) { let cert = SecCertificate::from_der(der_bytes).expect("invalid DER certificate"); println!("Subject summary: {}", cert.subject_summary()); // DER-encoded X.509 distinguished name let issuer_der = cert.issuer(); println!("Issuer DER length: {} bytes", issuer_der.len()); let subject_der = cert.subject(); println!("Subject DER length: {} bytes", subject_der.len()); // Serial number (returns CFError on failure) match cert.serial_number_bytes() { Ok(serial) => println!("Serial: {}", hex::encode(&serial)), Err(e) => eprintln!("Serial error: {:?}", e), } // SubjectPublicKeyInfo DER for certificate pinning if let Ok(Some(spki)) = cert.public_key_info_der() { println!("SPKI DER ({} bytes) for pinning", spki.len()); } // Round-trip back to DER let re_encoded = cert.to_der(); assert_eq!(der_bytes, re_encoded.as_slice()); } ``` ``` -------------------------------- ### Validate Certificate with Revocation Checking Source: https://context7.com/kornelski/rust-security-framework/llms.txt Validates a certificate against an SSL policy and requires OCSP revocation checking. Uses `SecPolicy::create_revocation` with `RevocationPolicy::OCSP_METHOD` and `RevocationPolicy::REQUIRE_POSITIVE_RESPONSE`. ```rust use security_framework::policy::{RevocationPolicy, SecPolicy}; use security_framework::secure_transport::SslProtocolSide; use security_framework::trust::SecTrust; use security_framework::certificate::SecCertificate; fn validate_with_revocation(cert_der: &[u8]) { let cert = SecCertificate::from_der(cert_der).unwrap(); let ssl_policy = SecPolicy::create_ssl(SslProtocolSide::CLIENT, Some("example.com")); // Require OCSP revocation checking let revocation_policy = SecPolicy::create_revocation( RevocationPolicy::OCSP_METHOD | RevocationPolicy::REQUIRE_POSITIVE_RESPONSE, ).unwrap(); let mut trust = SecTrust::create_with_certificates( &[cert], &[ssl_policy, revocation_policy], ).unwrap(); match trust.evaluate_with_error() { Ok(()) => println!("Certificate is valid and not revoked."), Err(e) => eprintln!("Validation failed: {:?}", e), } } ``` -------------------------------- ### SecRandom — cryptographically secure random bytes Source: https://context7.com/kornelski/rust-security-framework/llms.txt Provides access to Apple's cryptographically secure random number generator (`kSecRandomDefault`), generating bytes suitable for keys, nonces, and tokens. ```APIDOC ## `SecRandom` — cryptographically secure random bytes `SecRandom` provides access to Apple's cryptographically secure random number generator (`kSecRandomDefault`), generating bytes suitable for keys, nonces, and tokens. ```rust use security_framework::random::SecRandom; fn generate_random_token() -> [u8; 32] { let mut token = [0u8; 32]; SecRandom::default() .copy_bytes(&mut token) .expect("random byte generation failed"); println!("Random token: {}", hex::encode(token)); token } fn generate_nonce() -> Vec { let mut nonce = vec![0u8; 12]; // 96-bit nonce for AES-GCM SecRandom::default().copy_bytes(&mut nonce).unwrap(); nonce } ``` ``` -------------------------------- ### Evaluate Server Certificate Trust Source: https://context7.com/kornelski/rust-security-framework/llms.txt Evaluates a server certificate chain against an SSL policy, optionally trusting only custom anchor certificates. Requires the `SecCertificate`, `SecPolicy`, and `SecTrust` types. ```rust use security_framework::certificate::SecCertificate; use security_framework::policy::SecPolicy; use security_framework::secure_transport::SslProtocolSide; use security_framework::trust::SecTrust; fn evaluate_server_certificate(leaf_der: &[u8], ca_der: &[u8]) { let leaf = SecCertificate::from_der(leaf_der).unwrap(); let ca = SecCertificate::from_der(ca_der).unwrap(); // Create an SSL policy that validates the server hostname let policy = SecPolicy::create_ssl(SslProtocolSide::CLIENT, Some("example.com")); let mut trust = SecTrust::create_with_certificates(&[leaf], &[policy]).unwrap(); // Provide the CA as a custom anchor; only trust this CA trust.set_anchor_certificates(&[ca]).unwrap(); trust.set_trust_anchor_certificates_only(true).unwrap(); match trust.evaluate_with_error() { Ok(()) => println!("Certificate chain is trusted."), Err(e) => eprintln!("Trust evaluation failed: {:?}", e), } // Retrieve the evaluated chain (requires macos-12 feature or non-macOS) #[cfg(any(feature = "macos-12", not(target_os = "macos")))] for cert in trust.chain() { println!(" Chain member: {}", cert.subject_summary()); } } ``` -------------------------------- ### Generate Secure Enclave Key with Biometric Access Source: https://context7.com/kornelski/rust-security-framework/llms.txt Generates an EC key in the Secure Enclave, requiring biometric authentication for access. The private key is not exportable from the Secure Enclave. ```rust use security_framework::access_control::SecAccessControl; use security_framework::item::Location; use security_framework::key::{GenerateKeyOptions, KeyType, SecKey, Token}; fn generate_secure_enclave_key() { // Access control: require biometry to use the key let access = SecAccessControl::create_with_flags( security_framework_sys::access_control::kSecAttrAccessibleWhenUnlockedThisDeviceOnly, security_framework_sys::access_control::SecAccessControlCreateFlags::BIOMETRY_ANY, ).expect("access control creation failed"); let key = SecKey::new( GenerateKeyOptions::default() .set_key_type(KeyType::ec_sec_prime_random()) .set_size_in_bits(256) .set_token(Token::SecureEnclave) .set_label("Biometric Signing Key") .set_access_control(access), ).expect("Secure Enclave key generation failed"); println!("Secure Enclave key: {:?}", key); // The private key is NOT exportable from the Secure Enclave assert!(key.external_representation().is_none()); } ``` -------------------------------- ### `set_generic_password` / `get_generic_password` / `delete_generic_password` Source: https://context7.com/kornelski/rust-security-framework/llms.txt Provides CRUD operations for generic password entries in the system Keychain, identified by service and account names. Works on macOS and iOS. ```APIDOC ## `set_generic_password` / `get_generic_password` / `delete_generic_password` These functions provide simple CRUD access to generic password entries in the system Keychain, identified by a service name and account name. They work on both macOS and iOS. ```rust use security_framework::passwords::{ delete_generic_password, get_generic_password, set_generic_password, }; fn keychain_generic_password_roundtrip() { let service = "com.example.myapp"; let account = "alice@example.com"; let secret = b"hunter2"; // Store (creates or updates the entry) set_generic_password(service, account, secret) .expect("failed to set password"); // Retrieve let retrieved = get_generic_password(service, account) .expect("password not found"); assert_eq!(retrieved, secret); println!("Retrieved: {}", String::from_utf8_lossy(&retrieved)); // Update — just call set again; it upserts automatically set_generic_password(service, account, b"new-secret").unwrap(); // Delete delete_generic_password(service, account) .expect("failed to delete password"); // Confirm deletion assert!(get_generic_password(service, account).is_err()); } ``` ``` -------------------------------- ### Update Keychain Item Password Source: https://context7.com/kornelski/rust-security-framework/llms.txt Updates an existing keychain item's password atomically. It searches for the item using service and account, then updates its data. ```rust use core_foundation::data::CFData; use security_framework::item::{ update_item, ItemClass, ItemSearchOptions, ItemUpdateOptions, ItemUpdateValue, }; fn rotate_password(service: &str, account: &str, new_password: &[u8]) { let search = { let mut s = ItemSearchOptions::new(); s.class(ItemClass::generic_password()) .service(service) .account(account); s }; let update = { let mut u = ItemUpdateOptions::new(); u.set_value(ItemUpdateValue::Data(CFData::from_buffer(new_password))); u }; update_item(&search, &update).expect("failed to update keychain item"); println!("Password rotated for {account}@{service}"); } ``` -------------------------------- ### Internet Password CRUD Operations Source: https://context7.com/kornelski/rust-security-framework/llms.txt Manage internet password entries in the system Keychain, associating credentials with server, account, path, port, protocol, and authentication type. Works on macOS and iOS. ```rust use security_framework::passwords::{ delete_internet_password, get_internet_password, set_internet_password, }; use security_framework_sys::keychain::{SecAuthenticationType, SecProtocolType}; fn internet_password_example() { let server = "api.example.com"; let account = "bob"; let path = "/api/v1"; let port = Some(443u16); set_internet_password( server, None, // security domain (optional) account, path, port, SecProtocolType::HTTPS, SecAuthenticationType::HTMLForm, b"s3cr3t-token", ).expect("could not store internet password"); let pw = get_internet_password( server, None, account, path, port, SecProtocolType::HTTPS, SecAuthenticationType::HTMLForm, ).expect("internet password not found"); println!("Token: {}", String::from_utf8_lossy(&pw)); delete_internet_password( server, None, account, path, port, SecProtocolType::HTTPS, SecAuthenticationType::HTMLForm, ).unwrap(); } ``` -------------------------------- ### Generate Cryptographically Secure Random Bytes Source: https://context7.com/kornelski/rust-security-framework/llms.txt Generates cryptographically secure random bytes using Apple's default random number generator. Suitable for keys, nonces, and tokens. ```rust use security_framework::random::SecRandom; fn generate_random_token() -> [u8; 32] { let mut token = [0u8; 32]; SecRandom::default() .copy_bytes(&mut token) .expect("random byte generation failed"); println!("Random token: {}", hex::encode(token)); token } fn generate_nonce() -> Vec { let mut nonce = vec![0u8; 12]; // 96-bit nonce for AES-GCM SecRandom::default().copy_bytes(&mut nonce).unwrap(); nonce } ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.