Skip to main content

Jwk

Struct Jwk 

Source
pub struct Jwk { /* private fields */ }
Expand description

A JSON Web Key (RFC 7517).

A Jwk carries the common members (kty, use, key_ops, alg, kid), the public parameters of RFC 7518 and RFC 8037 (crv, x, y, n, e), the private parameters (d, p, q, dp, dq, qi, oth, k) and any other member in an insertion-ordered map, so a key round-trips through JSON with its extension members intact.

Private parameters never appear in Debug or Display output and are zeroized when the key is dropped. Jwk::public strips them; serde serialization keeps them, because a key store that persists private JWKs needs it to.

Members are kept as the base64url strings they arrive as. Nothing is validated when a key is parsed; the accessors that decode the material (Jwk::ed25519_public_bytes, Jwk::p256_public_bytes, …) and the operations that need it (Jwk::thumbprint_sha256, Jwk::to_decoding_key, the verifiers) report what is wrong.

§Examples

use identity_kit::jose::Jwk;

// The Ed25519 key of RFC 8037 Appendix A.2.
let jwk: Jwk = serde_json::from_str(
    r#"{"kty":"OKP","crv":"Ed25519","x":"11qYAYKxCrfVS_7TyWQHOg7hcvPapiMlrwIaaPcHURo"}"#,
)?;
assert_eq!(jwk.kty(), "OKP");
assert_eq!(jwk.crv(), Some("Ed25519"));
assert_eq!(jwk.ed25519_public_bytes()?.len(), 32);
assert_eq!(jwk.thumbprint_sha256()?, "kPrK_qmxVWaYVA9wwBF6Iuo3vVzz7TxHCTwXBygrS4k");

Implementations§

Source§

impl Jwk

Source

pub fn from_ed25519_public(public: &[u8]) -> Result<Self, JwkError>

An OKP key with crv Ed25519 from the 32-byte public key of RFC 8032.

§Errors

JwkError::InvalidKey when public is not 32 bytes or not a valid point.

Source

pub fn from_x25519_public(public: &[u8]) -> Result<Self, JwkError>

An OKP key with crv X25519 from the 32-byte public key of RFC 7748, for key agreement (RFC 8037 §3).

§Errors

JwkError::InvalidKeyLength when public is not 32 bytes.

Source

pub fn from_p256_public(sec1: &[u8]) -> Result<Self, JwkError>

An EC key with crv P-256 from a SEC1-encoded point, compressed or uncompressed.

§Errors

JwkError::InvalidKey when sec1 is not a valid P-256 point.

Source

pub fn from_secp256k1_public(sec1: &[u8]) -> Result<Self, JwkError>

Available on crate feature secp256k1 only.

An EC key with crv secp256k1 from a SEC1-encoded point, compressed or uncompressed.

§Errors

JwkError::InvalidKey when sec1 is not a valid secp256k1 point.

Source

pub fn from_rsa_public(n: &[u8], e: &[u8]) -> Result<Self, JwkError>

An RSA key from the big-endian modulus n and public exponent e.

Leading zero octets are dropped, as RFC 7518 §6.3.1 requires. The values are not checked beyond being non-empty, like the other parsers of this crate leave the rules of an algorithm to verification: DefaultVerifier and Jwk::to_decoding_key refuse a modulus shorter than 2048 bits (RFC 7518 §3.3, §3.5), and the verifier an otherwise unusable modulus or exponent, when the key is used.

§Errors

JwkError::InvalidKey when n or e is empty.

Source

pub fn from_spki_der(hint: KeyType, der: &[u8]) -> Result<Self, JwkError>

A key from a DER-encoded X.509 SubjectPublicKeyInfo (RFC 5280 §4.1.2.7), the form in which KMS and HSM backends return public keys.

hint is what the caller expects and selects the parser; a key of another type is an error, as is an RSA modulus of another size than the hint names.

§Errors
Source

pub fn kty(&self) -> &str

The key type (kty): OKP, EC, RSA or oct.

Source

pub fn crv(&self) -> Option<&str>

The curve (crv) of an EC or OKP key.

Source

pub fn x(&self) -> Option<&str>

The base64url x coordinate (EC) or public key (OKP).

Source

pub fn y(&self) -> Option<&str>

The base64url y coordinate of an EC key.

Source

pub fn n(&self) -> Option<&str>

The base64url RSA modulus n.

Source

pub fn e(&self) -> Option<&str>

The base64url RSA public exponent e.

Source

pub fn key_use(&self) -> Option<&str>

The public key use (use): sig or enc.

Source

pub fn key_ops(&self) -> Option<&[String]>

The key operations (key_ops), such as sign and verify.

Source

pub fn alg(&self) -> Option<&str>

The algorithm (alg) the key is intended for.

Source

pub fn kid(&self) -> Option<&str>

The key id (kid).

Source

pub fn additional(&self) -> &IndexMap<String, Value>

Members other than the ones this type models, in the order they were inserted.

Source

pub fn additional_mut(&mut self) -> &mut IndexMap<String, Value>

Mutable access to the members other than the ones this type models.

Source

pub fn is_private(&self) -> bool

Whether the key carries private parameters (d, p, q, dp, dq, qi, oth or k).

Source

pub fn with_kid(self, kid: impl Into<String>) -> Self

This key with its kid set.

Source

pub fn with_alg(self, alg: impl Into<String>) -> Self

This key with its alg set.

Source

pub fn with_key_use(self, key_use: impl Into<String>) -> Self

This key with its use set.

Source

pub fn with_key_ops<I, S>(self, key_ops: I) -> Self
where I: IntoIterator<Item = S>, S: Into<String>,

This key with its key_ops set.

Source

pub fn public(&self) -> Self

A copy of this key without private parameters.

Source

pub fn thumbprint_sha256(&self) -> Result<String, JwkError>

The RFC 7638 JWK thumbprint with SHA-256, as base64url.

The thumbprint hashes the required members of the key type (crv, kty, x, y for EC; crv, kty, x for OKP; e, kty, n for RSA; k, kty for oct) in lexicographic order with no whitespace, exactly as they appear in the key.

§Errors

JwkError::MissingMember when a required member is absent and JwkError::UnsupportedKeyType for any other kty.

§Examples
use identity_kit::jose::Jwk;

// RFC 7638 §3.1.
let jwk: Jwk = serde_json::from_str(r#"{
  "kty": "RSA",
  "n": "0vx7agoebGcQSuuPiLJXZptN9nndrQmbXEps2aiAFbWhM78LhWx4cbbfAAtVT86zwu1RK7aPFFxuhDR1L6tSoc_BJECPebWKRXjBZCiFV4n3oknjhMstn64tZ_2W-5JsGY4Hc5n9yBXArwl93lqt7_RN5w6Cf0h4QyQ5v-65YGjQR0_FDW2QvzqY368QQMicAtaSqzs8KJZgnYb9c7d0zgdAZHzu6qMQvRL5hajrn1n91CbOpbISD08qNLyrdkt-bFTWhAI4vMQFh6WeZu0fM4lFd2NcRwr3XPksINHaQ-G_xBniIqbw0Ls1jF44-csFCur-kEgU8awapJzKnqDKgw",
  "e": "AQAB",
  "alg": "RS256",
  "kid": "2011-04-29"
}"#)?;
assert_eq!(jwk.thumbprint_sha256()?, "NzbLsXh8uDCcd-6MNwXF4W_7noWXFZAfHkxZsRGC9Xs");
Source

pub fn ed25519_public_bytes(&self) -> Result<[u8; 32], JwkError>

The 32-byte Ed25519 public key of an OKP key with crv Ed25519.

§Errors

JwkError::UnexpectedKeyType for any other key, JwkError::MissingMember or JwkError::InvalidBase64Url for a broken x, and JwkError::InvalidKey when x is not a valid point.

Source

pub fn x25519_public_bytes(&self) -> Result<[u8; 32], JwkError>

The 32-byte X25519 public key of an OKP key with crv X25519.

§Errors

JwkError::UnexpectedKeyType for any other key, JwkError::MissingMember or JwkError::InvalidBase64Url for a broken x, and JwkError::InvalidKeyLength when x is not 32 bytes.

Source

pub fn p256_public_bytes(&self) -> Result<[u8; 65], JwkError>

The uncompressed SEC1 point (0x04 || x || y, 65 bytes) of an EC key with crv P-256.

§Errors

JwkError::UnexpectedKeyType for any other key, JwkError::MissingMember or JwkError::InvalidBase64Url for a broken x or y, and JwkError::InvalidKey when the coordinates are not a point on the curve.

Source

pub fn secp256k1_public_bytes(&self) -> Result<[u8; 65], JwkError>

Available on crate feature secp256k1 only.

The uncompressed SEC1 point (0x04 || x || y, 65 bytes) of an EC key with crv secp256k1.

§Errors

JwkError::UnexpectedKeyType for any other key, JwkError::MissingMember or JwkError::InvalidBase64Url for a broken x or y, and JwkError::InvalidKey when the coordinates are not a point on the curve.

Source

pub fn rsa_public_components(&self) -> Result<(Vec<u8>, Vec<u8>), JwkError>

The big-endian modulus n and public exponent e of an RSA key.

§Errors

JwkError::UnexpectedKeyType for any other key, JwkError::MissingMember or JwkError::InvalidBase64Url for a broken n or e.

Source

pub fn to_decoding_key(&self) -> Result<DecodingKey, JwkError>

A jsonwebtoken::DecodingKey for this key, so a JWT can be verified with jsonwebtoken.

Supports OKP/Ed25519, EC/P-256, EC/P-384 and RSA keys, the types jsonwebtoken can verify with. Private parameters are not needed and not used.

§Errors

JwkError::UnsupportedKeyType for any other key, JwkError::MissingMember when a required member is absent, JwkError::InvalidBase64Url for an RSA modulus or exponent that is not base64url, JwkError::InvalidKey for an RSA modulus shorter than 2048 bits (RFC 7518 §3.3, §3.5) and JwkError::DecodingKey when jsonwebtoken rejects the material.

Source§

impl Jwk

Source

pub fn from_multikey(multikey: &str) -> Result<Self, JwkError>

The key a Multikey string (z6Mk…) encodes.

The string is the base58btc multibase (z) of a multicodec header followed by the raw key; see KeyCodec for the key types understood.

§Errors
§Examples
use identity_kit::jose::Jwk;

// The Ed25519 key of the did:key specification's first example.
let jwk = Jwk::from_multikey("z6MkhaXgBZDvotDkL5257faiztiGiC2QtKLGpbnnEGta2doK")?;
assert_eq!((jwk.kty(), jwk.crv()), ("OKP", Some("Ed25519")));
assert_eq!(jwk.to_multikey()?, "z6MkhaXgBZDvotDkL5257faiztiGiC2QtKLGpbnnEGta2doK");
Source

pub fn to_multikey(&self) -> Result<String, JwkError>

This key as a Multikey string: base58btc multibase of the multicodec header and the raw public key. EC points are compressed; an RSA key is a PKCS #1 RSAPublicKey.

Only the public parameters are encoded.

§Errors

JwkError::UnsupportedKeyType for a key type without a KeyCodec, and the errors of the raw key accessors (Jwk::ed25519_public_bytes and friends) when the key does not decode.

Source§

impl Jwk

Source

pub fn from_pkcs1_der(der: &[u8]) -> Result<Self, JwkError>

An RSA key from a DER-encoded PKCS #1 RSAPublicKey (SEQUENCE { modulus INTEGER, publicExponent INTEGER }, RFC 8017 Appendix A.1.1).

This is for key store backends whose vault returns an RSA public key as PKCS #1 rather than as a SubjectPublicKeyInfo (for that, see Jwk::from_spki_der). The parser is strict DER: definite lengths in the fewest octets, non-negative minimally encoded INTEGERs, nothing after the SEQUENCE. It needs no Cargo feature.

Unlike Jwk::from_spki_der, it takes no KeyType and does not check the modulus size, as Jwk::from_rsa_public and Jwk::from_multikey do not: PKCS #1 carries no algorithm identifier for a hint to select a parser by, and DefaultVerifier rejects an unusable modulus, or one shorter than 2048 bits, when the key is used.

§Errors

JwkError::InvalidKey with key: "RSA" when der is not a DER RSAPublicKey.

§Examples
use identity_kit::jose::Jwk;

// `SEQUENCE { INTEGER 0x00c5, INTEGER 65537 }`: the leading zero keeps the modulus positive.
let der = [0x30, 0x09, 0x02, 0x02, 0x00, 0xc5, 0x02, 0x03, 0x01, 0x00, 0x01];
let jwk = Jwk::from_pkcs1_der(&der)?;
assert_eq!(jwk.rsa_public_components()?, (vec![0xc5], vec![0x01, 0x00, 0x01]));
assert_eq!(jwk.to_pkcs1_der()?, der);
Source

pub fn to_pkcs1_der(&self) -> Result<Vec<u8>, JwkError>

This RSA key’s public parameters as a DER-encoded PKCS #1 RSAPublicKey (RFC 8017 Appendix A.1.1), for key store backends whose vault takes that form.

The encoding is DER, so it is the same for every JWK of the same key.

§Errors

The errors of Jwk::rsa_public_components: JwkError::UnexpectedKeyType for any other key, JwkError::MissingMember or JwkError::InvalidBase64Url for a broken n or e; JwkError::InvalidKey when n or e is zero, which no RSAPublicKey that Jwk::from_pkcs1_der reads can hold.

Trait Implementations§

Source§

impl Clone for Jwk

Source§

fn clone(&self) -> Self

Returns a duplicate of the value. Read more
1.0.0 (const: unstable) · Source§

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

Performs copy-assignment from source. Read more
Source§

impl Debug for Jwk

Source§

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

Public members only; private parameters are shown as private: true.

Source§

impl<'de> Deserialize<'de> for Jwk

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 Display for Jwk

Source§

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

The public key as compact JSON, as Jwk::public serializes.

Source§

impl Eq for Jwk

Source§

impl PartialEq for Jwk

Source§

fn eq(&self, other: &Self) -> bool

Equality operator ==. Read more
1.0.0 (const: unstable) · Source§

fn ne(&self, other: &Rhs) -> bool

Inequality operator !=. Read more
Source§

impl PartialSchema for Jwk

Available on crate feature utoipa only.
Source§

fn schema() -> RefOr<Schema>

Return ref or schema of implementing type that can then be used to construct combined schemas.
Source§

impl Serialize for Jwk

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

impl StructuralPartialEq for Jwk

Source§

impl ToSchema for Jwk

Available on crate feature utoipa only.
Source§

fn name() -> Cow<'static, str>

Return name of the schema. Read more
Source§

fn schemas(schemas: &mut Vec<(String, RefOr<Schema>)>)

Implement reference utoipa::openapi::schema::Schemas for this type. Read more

Auto Trait Implementations§

§

impl Freeze for Jwk

§

impl RefUnwindSafe for Jwk

§

impl Send for Jwk

§

impl Sync for Jwk

§

impl Unpin for Jwk

§

impl UnsafeUnpin for Jwk

§

impl UnwindSafe for Jwk

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<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> DeserializeOwned for T
where T: for<'de> Deserialize<'de>,

Source§

impl<Q, K> Equivalent<K> for Q
where Q: Eq + ?Sized, K: Borrow<Q> + ?Sized,

Source§

fn equivalent(&self, key: &K) -> bool

Checks if this value is equivalent to the given key. Read more
Source§

impl<Q, K> Equivalent<K> for Q
where Q: Eq + ?Sized, K: Borrow<Q> + ?Sized,

Source§

fn equivalent(&self, key: &K) -> bool

Compare self to key and return true if they are equal.
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> PolicyExt for T
where T: ?Sized,

Source§

fn and<P, B, E>(self, other: P) -> And<T, P>
where T: Sized + 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: Sized + 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> ToString for T
where T: Display + ?Sized,

Source§

fn to_string(&self) -> String

Converts the given value to a String. Read more
Source§

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

Source§

type Error = !

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

fn try_from(value: U) -> Result<T, !>

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