Skip to main content

KeySet

Struct KeySet 

Source
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 included

Implementations§

Source§

impl KeySet

Source

pub fn new() -> Self

Creates a new empty KeySet.

§Examples
use jwk_simple::KeySet;

let jwks = KeySet::new();
assert!(jwks.is_empty());
Source

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);
Source

pub fn keys(&self) -> &[Key]

Returns a slice of all keys in the set.

Source

pub fn len(&self) -> usize

Returns the number of keys in the set.

Source

pub fn is_empty(&self) -> bool

Returns true if the set contains no keys.

Source

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);
Source

pub fn remove_by_kid(&mut self, kid: &str) -> Option<Key>

Removes and returns a key by its ID.

Source

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());
Source

pub fn signing_keys(&self) -> impl Iterator<Item = &Key>

Finds all signing keys.

A key is considered a signing key if:

  • It has key_ops containing sign or verify, OR (when key_ops is absent)
  • It has use: "sig", OR
  • It has neither use nor key_ops specified
§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.

Source

pub fn encryption_keys(&self) -> impl Iterator<Item = &Key>

Finds all encryption keys.

A key is considered an encryption key if:

  • It has key_ops containing encrypt, decrypt, wrapKey, or unwrapKey, OR (when key_ops is 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.

Source

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");
Source

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());
Source

pub fn iter(&self) -> impl Iterator<Item = &Key>

Returns an iterator over the keys.

Source

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.

Source

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.

Source

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_ops are included only if they contain that operation,
  • otherwise, keys with use are included only if use is compatible with the operation,
  • keys with neither key_ops nor use are 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);
Source

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.

Trait Implementations§

Source§

impl Clone for KeySet

Source§

fn clone(&self) -> KeySet

Returns a duplicate of the value. Read more
1.0.0 · Source§

fn clone_from(&mut self, source: &Self)

Performs copy-assignment from source. Read more
Source§

impl Debug for KeySet

Source§

fn fmt(&self, f: &mut Formatter<'_>) -> Result

Formats the value using the given formatter. Read more
Source§

impl Default for KeySet

Source§

fn default() -> KeySet

Returns the “default value” for a type. Read more
Source§

impl<'de> Deserialize<'de> for KeySet

Source§

fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
where D: Deserializer<'de>,

Deserialize this value from the given Serde deserializer. Read more
Source§

impl Index<usize> for KeySet

Source§

type Output = Key

The returned type after indexing.
Source§

fn index(&self, index: usize) -> &Self::Output

Performs the indexing (container[index]) operation. Read more
Source§

impl<'a> IntoIterator for &'a KeySet

Source§

type Item = &'a Key

The type of the elements being iterated over.
Source§

type IntoIter = Iter<'a, Key>

Which kind of iterator are we turning this into?
Source§

fn into_iter(self) -> Self::IntoIter

Creates an iterator from a value. Read more
Source§

impl IntoIterator for KeySet

Source§

type Item = Key

The type of the elements being iterated over.
Source§

type IntoIter = IntoIter<Key>

Which kind of iterator are we turning this into?
Source§

fn into_iter(self) -> Self::IntoIter

Creates an iterator from a value. Read more
Source§

impl KeyStore for KeySet

Source§

fn get_keyset<'life0, 'async_trait>( &'life0 self, ) -> Pin<Box<dyn Future<Output = Result<KeySet>> + Send + 'async_trait>>
where Self: 'async_trait, 'life0: 'async_trait,

Gets all available keys as a KeySet. Read more
Source§

fn get_key<'life0, 'life1, 'async_trait>( &'life0 self, kid: &'life1 str, ) -> Pin<Box<dyn Future<Output = Result<Option<Key>>> + Send + 'async_trait>>
where Self: 'async_trait, 'life0: 'async_trait, 'life1: 'async_trait,

Gets a key by its key ID (kid). Read more
Source§

impl Serialize for KeySet

Source§

fn serialize<__S>(&self, __serializer: __S) -> Result<__S::Ok, __S::Error>
where __S: Serializer,

Serialize this value into the given Serde serializer. Read more

Auto Trait Implementations§

Blanket Implementations§

Source§

impl<T> Any for T
where T: 'static + ?Sized,

Source§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
Source§

impl<'a, T, E> AsTaggedExplicit<'a, E> for T
where T: 'a,

Source§

fn explicit(self, class: Class, tag: u32) -> TaggedParser<'a, Explicit, Self, E>

Source§

impl<'a, T, E> AsTaggedImplicit<'a, E> for T
where T: 'a,

Source§

fn implicit( self, class: Class, constructed: bool, tag: u32, ) -> TaggedParser<'a, Implicit, Self, E>

Source§

impl<T> Borrow<T> for T
where T: ?Sized,

Source§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
Source§

impl<T> BorrowMut<T> for T
where T: ?Sized,

Source§

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
Source§

impl<T> CloneToUninit for T
where T: Clone,

Source§

unsafe fn clone_to_uninit(&self, dest: *mut u8)

🔬This is a nightly-only experimental API. (clone_to_uninit)
Performs copy-assignment from self to dest. Read more
Source§

impl<T> From<T> for T

Source§

fn from(t: T) -> T

Returns the argument unchanged.

Source§

impl<T> Instrument for T

Source§

fn instrument(self, span: Span) -> Instrumented<Self>

Instruments this type with the provided Span, returning an Instrumented wrapper. Read more
Source§

fn in_current_span(self) -> Instrumented<Self>

Instruments this type with the current Span, returning an Instrumented wrapper. Read more
Source§

impl<T, U> Into<U> for T
where U: From<T>,

Source§

fn into(self) -> U

Calls U::from(self).

That is, this conversion is whatever the implementation of From<T> for U chooses to do.

Source§

impl<T> Pointable for T

Source§

const ALIGN: usize

The alignment of pointer.
Source§

type Init = T

The type for initializers.
Source§

unsafe fn init(init: <T as Pointable>::Init) -> usize

Initializes a with the given initializer. Read more
Source§

unsafe fn deref<'a>(ptr: usize) -> &'a T

Dereferences the given pointer. Read more
Source§

unsafe fn deref_mut<'a>(ptr: usize) -> &'a mut T

Mutably dereferences the given pointer. Read more
Source§

unsafe fn drop(ptr: usize)

Drops the object pointed to by the given pointer. Read more
Source§

impl<T> PolicyExt for T
where T: ?Sized,

Source§

fn and<P, B, E>(self, other: P) -> And<T, P>
where T: Policy<B, E>, P: Policy<B, E>,

Create a new Policy that returns Action::Follow only if self and other return Action::Follow. Read more
Source§

fn or<P, B, E>(self, other: P) -> Or<T, P>
where T: Policy<B, E>, P: Policy<B, E>,

Create a new Policy that returns Action::Follow if either self or other returns Action::Follow. Read more
Source§

impl<T> Same for T

Source§

type Output = T

Should always be Self
Source§

impl<T> ToOwned for T
where T: Clone,

Source§

type Owned = T

The resulting type after obtaining ownership.
Source§

fn to_owned(&self) -> T

Creates owned data from borrowed data, usually by cloning. Read more
Source§

fn clone_into(&self, target: &mut T)

Uses borrowed data to replace owned data, usually by cloning. Read more
Source§

impl<T, U> TryFrom<U> for T
where U: Into<T>,

Source§

type Error = Infallible

The type returned in the event of a conversion error.
Source§

fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::Error>

Performs the conversion.
Source§

impl<T, U> TryInto<U> for T
where U: TryFrom<T>,

Source§

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
Source§

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.
Source§

impl<V, T> VZip<V> for T
where V: MultiLane<T>,

Source§

fn vzip(self) -> V

Source§

impl<T> WithSubscriber for T

Source§

fn with_subscriber<S>(self, subscriber: S) -> WithDispatch<Self>
where S: Into<Dispatch>,

Attaches the provided Subscriber to this type, returning a WithDispatch wrapper. Read more
Source§

fn with_current_subscriber(self) -> WithDispatch<Self>

Attaches the current default Subscriber to this type, returning a WithDispatch wrapper. Read more
Source§

impl<T> DeserializeOwned for T
where T: for<'de> Deserialize<'de>,