pub struct VerifyingKey<D>
where D: Digest,
{ /* private fields */ }
Expand description

Verifying key for RSASSA-PKCS1-v1_5 signatures as described in RFC8017 § 8.2.

Implementations§

source§

impl<D> VerifyingKey<D>
where D: Digest + AssociatedOid,

source

pub fn new(key: RsaPublicKey) -> VerifyingKey<D>

Create a new verifying key with a prefix for the digest D.

Examples found in repository?
examples/rfc7515a2.rs (line 118)
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
fn main() -> Result<(), Box<dyn std::error::Error>> {
    // This key is from RFC 7515, Appendix A.2. Provide your own key instead!
    // The key here is stored as a PKCS#8 PEM file, but you can leverage
    // RustCrypto to load a variety of other formats.
    let key = rsa::RsaPrivateKey::from_pkcs8_pem(include_str!(concat!(
        env!("CARGO_MANIFEST_DIR"),
        "/examples/rfc7515a2.pem"
    )))
    .unwrap();

    // We will sign the JWT with the RS256 algorithm: RSA with SHA-256.
    // RsaPkcs1v15 is really an alias to the digital signature algorithm
    // implementation in the `rsa` crate, but provided in JAWS to make
    // it clear which types are compatible with JWTs.
    let alg = rsa::pkcs1v15::SigningKey::<Sha256>::new(key);

    // Claims can combine registered and custom fields. The claims object
    // can be any type which implements [serde::Serialize].
    let claims: Claims<serde_json::Value, (), String, (), ()> = Claims {
        registered: RegisteredClaims {
            subject: "1234567890".to_string().into(),
            ..Default::default()
        },
        claims: json!({
            "name": "John Doe",
            "admin": true,
        }),
    };

    // Create a token with the default headers, and no custom headers.
    // The unit type can be used here because it implements [serde::Serialize],
    // but a custom type could be passed if we wanted to have custom header
    // fields.
    let mut token = Token::compact((), claims);
    // We can modify the headers freely before signing the JWT. In this case,
    // we provide the `typ` header, which is optional in the JWT spec.
    *token.header_mut().r#type() = Some("JWT".to_string());

    // We can also ask that some fields be derived from the signing key, for example,
    // this will derive the JWK field in the header from the signing key.
    token.header_mut().key().derived();

    println!("Initial JWT");

    // Initially the JWT has no defined signature:
    println!("JWT:");
    println!("{}", token.formatted());

    // Sign the token with the algorithm, and print the result.
    let signed = token.sign(&alg).unwrap();

    println!("Signed JWT");

    println!("JWT:");
    println!("{}", signed.formatted());
    println!("Token: {}", signed.rendered().unwrap());

    // We can't modify the token after signing it (that would change the signature)
    // but we can access fields and read from them:
    println!(
        "Type: {:?}, Algorithm: {:?}",
        signed.header().r#type(),
        signed.header().algorithm(),
    );

    // We can also verify tokens.
    let token: Token<Claims<serde_json::Value>, Unverified<()>, Compact> =
        signed.rendered().unwrap().parse().unwrap();

    println!("Parsed JWT");

    // Unverified tokens can be printed for debugging, but there is deliberately
    // no access to the payload, only to the header fields.
    println!("JWT:");
    println!("{}", token.formatted());

    // We can use the JWK to verify that the token is signed with the correct key.
    let hdr = token.header();
    let jwk = hdr.key().unwrap();
    let key = rsa_jwk_reader::rsa_pub(&serde_json::to_value(jwk).unwrap());

    assert_eq!(&key, alg.verifying_key().as_ref());

    let alg: rsa::pkcs1v15::VerifyingKey<Sha256> = rsa::pkcs1v15::VerifyingKey::new(key);

    // We can't access the claims until we verify the token.
    let verified = token.verify(&alg).unwrap();

    println!("Verified JWT");
    println!("JWT:");
    println!("{}", verified.formatted());
    println!(
        "Payload: \n{}",
        serde_json::to_string_pretty(&verified.payload()).unwrap()
    );

    Ok(())
}
source

pub fn new_with_prefix(key: RsaPublicKey) -> VerifyingKey<D>

👎Deprecated since 0.9.0: use VerifyingKey::new instead

Create a new verifying key with a prefix for the digest D.

source§

impl<D> VerifyingKey<D>
where D: Digest,

source

pub fn new_unprefixed(key: RsaPublicKey) -> VerifyingKey<D>

Create a new verifying key from an RSA public key with an empty prefix.

Note: unprefixed signatures are uncommon

In most cases you’ll want to use VerifyingKey::new instead.

Trait Implementations§

source§

impl<D> AsRef<RsaPublicKey> for VerifyingKey<D>
where D: Digest,

source§

fn as_ref(&self) -> &RsaPublicKey

Converts this type into a shared reference of the (usually inferred) input type.
source§

impl<D> AssociatedAlgorithmIdentifier for VerifyingKey<D>
where D: Digest,

§

type Params = AnyRef<'static>

Algorithm parameters.
source§

const ALGORITHM_IDENTIFIER: AlgorithmIdentifier<AnyRef<'static>> = pkcs1::ALGORITHM_ID

AlgorithmIdentifier for this structure.
source§

impl<D> Clone for VerifyingKey<D>
where D: Digest,

source§

fn clone(&self) -> VerifyingKey<D>

Returns a copy 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<D> Debug for VerifyingKey<D>
where D: Debug + Digest,

source§

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

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

impl<D> DigestVerifier<D, Signature> for VerifyingKey<D>
where D: Digest,

source§

fn verify_digest(&self, digest: D, signature: &Signature) -> Result<(), Error>

Verify the signature against the given Digest output.
source§

impl<D> EncodePublicKey for VerifyingKey<D>
where D: Digest,

source§

fn to_public_key_der(&self) -> Result<Document, Error>

Serialize a [Document] containing a SPKI-encoded public key.
§

fn to_public_key_pem(&self, line_ending: LineEnding) -> Result<String, Error>

Serialize this public key as PEM-encoded SPKI with the given LineEnding.
§

fn write_public_key_der_file(&self, path: impl AsRef<Path>) -> Result<(), Error>

Write ASN.1 DER-encoded public key to the given path
§

fn write_public_key_pem_file( &self, path: impl AsRef<Path>, line_ending: LineEnding ) -> Result<(), Error>

Write ASN.1 DER-encoded public key to the given path
source§

impl<D> From<RsaPublicKey> for VerifyingKey<D>
where D: Digest,

source§

fn from(key: RsaPublicKey) -> VerifyingKey<D>

Converts to this type from the input type.
source§

impl JWKeyType for VerifyingKey<Sha256>

source§

const KEY_TYPE: &'static str = "RSA"

The string used to identify the JWK type in the kty field.
source§

impl JWKeyType for VerifyingKey<Sha512>

source§

const KEY_TYPE: &'static str = "RSA"

The string used to identify the JWK type in the kty field.
source§

impl JWKeyType for VerifyingKey<Sha384>

source§

const KEY_TYPE: &'static str = "RSA"

The string used to identify the JWK type in the kty field.
source§

impl JoseAlgorithm for VerifyingKey<Sha256>

source§

const IDENTIFIER: AlgorithmIdentifier = crate::algorithms::AlgorithmIdentifier::RS256

The identifier for this algorithm when used in a JWT registered header. Read more
§

type Signature = Signature

The type of the signature, which must support encoding.
source§

impl JoseAlgorithm for VerifyingKey<Sha512>

source§

const IDENTIFIER: AlgorithmIdentifier = crate::algorithms::AlgorithmIdentifier::RS512

The identifier for this algorithm when used in a JWT registered header. Read more
§

type Signature = Signature

The type of the signature, which must support encoding.
source§

impl JoseAlgorithm for VerifyingKey<Sha384>

source§

const IDENTIFIER: AlgorithmIdentifier = crate::algorithms::AlgorithmIdentifier::RS384

The identifier for this algorithm when used in a JWT registered header. Read more
§

type Signature = Signature

The type of the signature, which must support encoding.
source§

impl JoseDigestAlgorithm for VerifyingKey<Sha256>

§

type Digest = CoreWrapper<CtVariableCoreWrapper<Sha256VarCore, UInt<UInt<UInt<UInt<UInt<UInt<UTerm, B1>, B0>, B0>, B0>, B0>, B0>, OidSha256>>

The digest algorithm used by this signature.
source§

impl JoseDigestAlgorithm for VerifyingKey<Sha512>

§

type Digest = CoreWrapper<CtVariableCoreWrapper<Sha512VarCore, UInt<UInt<UInt<UInt<UInt<UInt<UInt<UTerm, B1>, B0>, B0>, B0>, B0>, B0>, B0>, OidSha512>>

The digest algorithm used by this signature.
source§

impl JoseDigestAlgorithm for VerifyingKey<Sha384>

§

type Digest = CoreWrapper<CtVariableCoreWrapper<Sha512VarCore, UInt<UInt<UInt<UInt<UInt<UInt<UTerm, B1>, B1>, B0>, B0>, B0>, B0>, OidSha384>>

The digest algorithm used by this signature.
source§

impl<D> PrehashVerifier<Signature> for VerifyingKey<D>
where D: Digest,

source§

fn verify_prehash( &self, prehash: &[u8], signature: &Signature ) -> Result<(), Error>

Use Self to verify that the provided signature for a given message prehash is authentic. Read more
source§

impl SerializeJWK for VerifyingKey<Sha256>

source§

fn parameters(&self) -> Vec<(String, Value)>

Return a list of parameters to be serialized in the JWK.
source§

impl SerializeJWK for VerifyingKey<Sha512>

source§

fn parameters(&self) -> Vec<(String, Value)>

Return a list of parameters to be serialized in the JWK.
source§

impl SerializeJWK for VerifyingKey<Sha384>

source§

fn parameters(&self) -> Vec<(String, Value)>

Return a list of parameters to be serialized in the JWK.
source§

impl<D> SignatureAlgorithmIdentifier for VerifyingKey<D>
where D: Digest + RsaSignatureAssociatedOid,

§

type Params = AnyRef<'static>

Algorithm parameters.
source§

const SIGNATURE_ALGORITHM_IDENTIFIER: AlgorithmIdentifier<AnyRef<'static>> = _

AlgorithmIdentifier for the corresponding singature system.
source§

impl<D> TryFrom<SubjectPublicKeyInfo<AnyRef<'_>, BitStringRef<'_>>> for VerifyingKey<D>
where D: Digest + AssociatedOid,

§

type Error = Error

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

fn try_from( spki: SubjectPublicKeyInfo<AnyRef<'_>, BitStringRef<'_>> ) -> Result<VerifyingKey<D>, Error>

Performs the conversion.
source§

impl<D> Verifier<Signature> for VerifyingKey<D>
where D: Digest,

source§

fn verify(&self, msg: &[u8], signature: &Signature) -> Result<(), Error>

Use Self to verify that the provided signature for a given message bytestring is authentic. Read more

Auto Trait Implementations§

§

impl<D> RefUnwindSafe for VerifyingKey<D>
where D: RefUnwindSafe,

§

impl<D> Send for VerifyingKey<D>
where D: Send,

§

impl<D> Sync for VerifyingKey<D>
where D: Sync,

§

impl<D> Unpin for VerifyingKey<D>
where D: Unpin,

§

impl<D> UnwindSafe for VerifyingKey<D>
where D: UnwindSafe,

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
§

impl<T> DecodePublicKey for T
where T: for<'a> TryFrom<SubjectPublicKeyInfo<AnyRef<'a>, BitStringRef<'a>>, Error = Error>,

§

fn from_public_key_der(bytes: &[u8]) -> Result<T, Error>

Deserialize object from ASN.1 DER-encoded [SubjectPublicKeyInfo] (binary format).
§

fn from_public_key_pem(s: &str) -> Result<Self, Error>

Deserialize PEM-encoded [SubjectPublicKeyInfo]. Read more
§

fn read_public_key_der_file(path: impl AsRef<Path>) -> Result<Self, Error>

Load public key object from an ASN.1 DER-encoded file on the local filesystem (binary format).
§

fn read_public_key_pem_file(path: impl AsRef<Path>) -> Result<Self, Error>

Load public key object from a PEM-encoded file on the local filesystem.
§

impl<T> DecodeRsaPublicKey for T
where T: for<'a> TryFrom<SubjectPublicKeyInfo<AnyRef<'a>, BitStringRef<'a>>, Error = Error>,

§

fn from_pkcs1_der(public_key: &[u8]) -> Result<T, Error>

Deserialize object from ASN.1 DER-encoded [RsaPublicKey] (binary format).
§

fn from_pkcs1_pem(s: &str) -> Result<Self, Error>

Deserialize PEM-encoded [RsaPublicKey]. Read more
§

fn read_pkcs1_der_file(path: impl AsRef<Path>) -> Result<Self, Error>

Load [RsaPublicKey] from an ASN.1 DER-encoded file on the local filesystem (binary format).
§

fn read_pkcs1_pem_file(path: impl AsRef<Path>) -> Result<Self, Error>

Load [RsaPublicKey] from a PEM-encoded file on the local filesystem.
§

impl<T> DynAssociatedAlgorithmIdentifier for T
where T: AssociatedAlgorithmIdentifier,

§

fn algorithm_identifier(&self) -> Result<AlgorithmIdentifier<Any>, Error>

AlgorithmIdentifier for this structure.
§

impl<T> DynSignatureAlgorithmIdentifier for T
where T: SignatureAlgorithmIdentifier,

§

fn signature_algorithm_identifier( &self ) -> Result<AlgorithmIdentifier<Any>, Error>

AlgorithmIdentifier for the corresponding singature system.
§

impl<T> EncodeRsaPublicKey for T
where T: EncodePublicKey,

§

fn to_pkcs1_der(&self) -> Result<Document, Error>

Serialize a [Document] containing a PKCS#1-encoded public key.
§

fn to_pkcs1_pem(&self, line_ending: LineEnding) -> Result<String, Error>

Serialize this public key as PEM-encoded PKCS#1 with the given line ending.
§

fn write_pkcs1_der_file(&self, path: impl AsRef<Path>) -> Result<(), Error>

Write ASN.1 DER-encoded public key to the given path.
§

fn write_pkcs1_pem_file( &self, path: impl AsRef<Path>, line_ending: LineEnding ) -> Result<(), Error>

Write ASN.1 DER-encoded public key to the given path.
source§

impl<T> From<T> for T

source§

fn from(t: T) -> T

Returns the argument unchanged.

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> Same for T

§

type Output = T

Should always be Self
source§

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

§

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

§

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

§

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

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

§

fn vzip(self) -> V