pub struct KeySet { /* private fields */ }Expand description
A JSON Web Key Set (RFC 7517 Section 5).
A KeySet contains a collection of keys that can be looked up by various
criteria such as key ID (kid), algorithm, or key use.
§RFC Compliance
Per RFC 7517 Section 5:
“Implementations SHOULD ignore JWKs within a JWK Set that use ‘kty’ (key type) values that are not understood by them, that are missing required members, or for which values are out of the supported ranges.”
This implementation follows this guidance by silently skipping keys with
unknown kty values, missing required members, or invalid key parameter
values during deserialization rather than failing.
§Examples
Parse a JWKS from JSON:
use jwk_simple::KeySet;
let json = r#"{
"keys": [
{
"kty": "RSA",
"kid": "key-1",
"use": "sig",
"n": "0vx7agoebGcQSuuPiLJXZptN9nndrQmbXEps2aiAFbWhM78LhWx4cbbfAAtVT86zwu1RK7aPFFxuhDR1L6tSoc_BJECPebWKRXjBZCiFV4n3oknjhMstn64tZ_2W-5JsGY4Hc5n9yBXArwl93lqt7_RN5w6Cf0h4QyQ5v-65YGjQR0_FDW2QvzqY368QQMicAtaSqzs8KJZgnYb9c7d0zgdAZHzu6qMQvRL5hajrn1n91CbOpbISD08qNLyrdkt-bFTWhAI4vMQFh6WeZu0fM4lFd2NcRwr3XPksINHaQ-G_xBniIqbw0Ls1jF44-csFCur-kEgU8awapJzKnqDKgw",
"e": "AQAB"
}
]
}"#;
let jwks: KeySet = serde_json::from_str(json).unwrap();
assert_eq!(jwks.len(), 1);Keys that cannot be parsed are silently skipped:
use jwk_simple::KeySet;
let json = r#"{
"keys": [
{"kty": "UNKNOWN", "data": "ignored"},
{"kty": "oct", "k": "AQAB"}
]
}"#;
let jwks: KeySet = serde_json::from_str(json).unwrap();
assert_eq!(jwks.len(), 1); // Only the "oct" key is includedImplementations§
Source§impl KeySet
impl KeySet
Sourcepub fn new() -> Self
pub fn new() -> Self
Creates a new empty KeySet.
§Examples
use jwk_simple::KeySet;
let jwks = KeySet::new();
assert!(jwks.is_empty());Sourcepub fn from_keys_lossy(keys: Vec<Key>) -> Self
pub fn from_keys_lossy(keys: Vec<Key>) -> Self
Creates a key set from a list of keys, silently dropping invalid ones.
This matches the deserialization behavior: keys that fail
Key::validate are silently skipped.
Use KeySet::add_key for validated insertion that reports errors.
§Examples
use jwk_simple::{Key, KeyParams, KeySet, SymmetricParams};
use jwk_simple::encoding::Base64UrlBytes;
let key = Key::new(KeyParams::Symmetric(SymmetricParams::new(
Base64UrlBytes::new(vec![0u8; 32]),
)));
let jwks = KeySet::from_keys_lossy(vec![key]);
assert_eq!(jwks.len(), 1);Sourcepub fn add_key(&mut self, key: Key) -> Result<()>
pub fn add_key(&mut self, key: Key) -> Result<()>
Adds a key to the set after validating it.
Runs the same validation as Key::validate: structural parameter
checks, use/key_ops consistency, and certificate metadata.
§Errors
Returns an error if the key fails validation.
§Examples
use jwk_simple::{Key, KeyParams, KeySet, SymmetricParams};
use jwk_simple::encoding::Base64UrlBytes;
let mut jwks = KeySet::new();
let key = Key::new(KeyParams::Symmetric(SymmetricParams::new(
Base64UrlBytes::new(vec![0u8; 32]),
)));
jwks.add_key(key).unwrap();
assert_eq!(jwks.len(), 1);Sourcepub fn remove_by_kid(&mut self, kid: &str) -> Option<Key>
pub fn remove_by_kid(&mut self, kid: &str) -> Option<Key>
Removes and returns a key by its ID.
Sourcepub fn get_by_kid(&self, kid: &str) -> Option<&Key>
pub fn get_by_kid(&self, kid: &str) -> Option<&Key>
Finds a key by its ID (kid).
§Examples
use jwk_simple::KeySet;
let json = r#"{"keys": [{"kty": "oct", "kid": "my-key", "k": "AQAB"}]}"#;
let jwks: KeySet = serde_json::from_str(json).unwrap();
let key = jwks.get_by_kid("my-key");
assert!(key.is_some());
let missing = jwks.get_by_kid("unknown");
assert!(missing.is_none());Sourcepub fn signing_keys(&self) -> impl Iterator<Item = &Key>
pub fn signing_keys(&self) -> impl Iterator<Item = &Key>
Finds all signing keys.
A key is considered a signing key if:
- It has
key_opscontainingsignorverify, OR (whenkey_opsis absent) - It has
use: "sig", OR - It has neither
usenorkey_opsspecified
§Security
This is a discovery helper. Do not use it as a cryptographic trust gate.
For security-sensitive selection, use KeySet::selector and
KeySelector::select.
Sourcepub fn encryption_keys(&self) -> impl Iterator<Item = &Key>
pub fn encryption_keys(&self) -> impl Iterator<Item = &Key>
Finds all encryption keys.
A key is considered an encryption key if:
- It has
key_opscontainingencrypt,decrypt,wrapKey, orunwrapKey, OR (whenkey_opsis absent) - It has
use: "enc"
§Security
This is a discovery helper. Do not use it as a cryptographic trust gate.
For security-sensitive selection, use KeySet::selector and
KeySelector::select.
Sourcepub fn first_signing_key(&self) -> Option<&Key>
pub fn first_signing_key(&self) -> Option<&Key>
Returns the first signing key, if any.
This is a convenience method for cases where only one signing key is expected.
§Security
This is a discovery helper. Do not use it as a cryptographic trust gate.
For security-sensitive selection, use KeySet::selector and
KeySelector::select.
§Examples
use jwk_simple::KeySet;
let json = r#"{"keys": [{"kty": "RSA", "use": "sig", "n": "AQAB", "e": "AQAB"}]}"#;
let jwks: KeySet = serde_json::from_str(json).unwrap();
let key = jwks.first_signing_key().expect("expected a signing key");Sourcepub fn first(&self) -> Option<&Key>
pub fn first(&self) -> Option<&Key>
Returns the first key, if any.
§Examples
use jwk_simple::KeySet;
let jwks = KeySet::new();
assert!(jwks.first().is_none());Sourcepub fn validate(&self) -> Result<()>
pub fn validate(&self) -> Result<()>
Validates the structural integrity and metadata consistency of all keys
in the set (see Key::validate).
This is a context-free structural check: it does not validate algorithm
suitability, key strength for a specific algorithm, or operation intent,
even when the alg field is set on a key. Use Key::validate_for_use
for those checks.
§Errors
Returns the first validation error encountered, if any.
Sourcepub fn get_by_thumbprint(&self, thumbprint: &str) -> Option<&Key>
pub fn get_by_thumbprint(&self, thumbprint: &str) -> Option<&Key>
Finds a key by its JWK thumbprint (RFC 7638).
§Performance
This method computes the SHA-256 thumbprint of each key in the set on
every call, making it O(n) hash computations per lookup. For hot paths
(e.g., verifying JWTs in a web server), consider caching thumbprints
externally or using get_by_kid instead.
Thumbprints are derived from public key parameters (RFC 7638), so this uses standard equality. The iterator scan short-circuits on first match.
§Security
This method is intended for discovery and cache lookups, not as a standalone security gate.
Sourcepub fn find<'a, 'f>(
&'a self,
filter: KeyFilter<'f>,
) -> impl Iterator<Item = &'a Key> + 'a
pub fn find<'a, 'f>( &'a self, filter: KeyFilter<'f>, ) -> impl Iterator<Item = &'a Key> + 'a
Finds keys by optional discovery criteria.
This method is for discovery/filtering only and does not provide cryptographic suitability guarantees.
When filter.op is set:
- keys with explicit
key_opsare included only if they contain that operation, - otherwise, keys with
useare included only ifuseis compatible with the operation, - keys with neither
key_opsnoruseare treated as discovery candidates and pass through.
Unknown operations in discovery mode are passthrough for use-only keys:
they only filter keys that declare explicit key_ops and include the
unknown operation.
Keys that declare neither key_ops nor use also pass through.
§Examples
use jwk_simple::{Algorithm, KeyFilter, KeySet, KeyType};
let json = r#"{"keys": [
{"kty": "RSA", "kid": "r1", "alg": "RS256", "n": "AQAB", "e": "AQAB"},
{"kty": "EC", "kid": "e1", "alg": "ES256", "crv": "P-256", "x": "MKBCTNIcKUSDii11ySs3526iDZ8AiTo7Tu6KPAqv7D4", "y": "4Etl6SRW2YiLUrN5vfvVHuhp7x8PxltmWWlbbM4IFyM"}
]}"#;
let jwks: KeySet = serde_json::from_str(json).unwrap();
let rsa_rs256 = KeyFilter::new()
.with_kty(KeyType::Rsa)
.with_alg(Algorithm::Rs256);
assert_eq!(jwks.find(rsa_rs256).count(), 1);Sourcepub fn selector(&self, allowed_verify_algs: &[Algorithm]) -> KeySelector<'_>
pub fn selector(&self, allowed_verify_algs: &[Algorithm]) -> KeySelector<'_>
Creates a strict selector bound to this key set.
allowed_verify_algs applies only to KeyOperation::Verify.
For non-verify operations (for example KeyOperation::Sign),
this allowlist is not consulted.
Strict selection failures are returned by KeySelector::select.