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

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

Implementations§

source§

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

source

pub fn new(key: RsaPrivateKey) -> SigningKey<D>

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

Examples found in repository?
examples/acme-new-account.rs (line 50)
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
fn main() {
    // 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);

    let payload = json!({
      "termsOfServiceAgreed": true,
      "contact": [
        "mailto:cert-admin@example.org",
        "mailto:admin@example.org"
      ]
    });

    let header = json!({
        "nonce": "6S8IqOGY7eL2lsGoTZYifg",
        "url": "https://example.com/acme/new-account"
    });

    // Create a token with the default headers, and no custom headers.
    let mut token = Token::new(payload, header, Compact);
    // Request that the token header include a JWK field.
    token.header_mut().key().derived();

    // Sign the token with the algorithm and key we specified above.
    let signed = token.sign(&alg).unwrap();

    // Print the token in the ACME example format.
    println!("{}", signed.formatted());
}
More examples
Hide additional examples
examples/rfc7515a2.rs (line 49)
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 random<R>(rng: &mut R, bit_size: usize) -> Result<SigningKey<D>, Error>
where R: CryptoRngCore + ?Sized,

Generate a new signing key with a prefix for the digest D.

source

pub fn new_with_prefix(key: RsaPrivateKey) -> SigningKey<D>

👎Deprecated since 0.9.0: use SigningKey::new instead

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

source

pub fn random_with_prefix<R>( rng: &mut R, bit_size: usize ) -> Result<SigningKey<D>, Error>
where R: CryptoRngCore + ?Sized,

👎Deprecated since 0.9.0: use SigningKey::random instead

Generate a new signing key with a prefix for the digest D.

source§

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

source

pub fn new_unprefixed(key: RsaPrivateKey) -> SigningKey<D>

Create a new signing key from the give RSA private key with an empty prefix.

Note: unprefixed signatures are uncommon

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

source

pub fn random_unprefixed<R>( rng: &mut R, bit_size: usize ) -> Result<SigningKey<D>, Error>
where R: CryptoRngCore + ?Sized,

Generate a new signing key with an empty prefix.

Trait Implementations§

source§

impl<D> AsRef<RsaPrivateKey> for SigningKey<D>
where D: Digest,

source§

fn as_ref(&self) -> &RsaPrivateKey

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

impl<D> AssociatedAlgorithmIdentifier for SigningKey<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 SigningKey<D>
where D: Clone + Digest,

source§

fn clone(&self) -> SigningKey<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 SigningKey<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> DigestSigner<D, Signature> for SigningKey<D>
where D: Digest,

source§

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

Attempt to sign the given prehashed message Digest, returning a digital signature on success, or an error if something went wrong.
source§

fn sign_digest(&self, digest: D) -> S

Sign the given prehashed message Digest, returning a signature. Read more
source§

impl<D> EncodePrivateKey for SigningKey<D>
where D: Digest,

source§

fn to_pkcs8_der(&self) -> Result<SecretDocument, Error>

Serialize a [SecretDocument] containing a PKCS#8-encoded private key.
source§

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

Serialize this private key as PEM-encoded PKCS#8 with the given LineEnding.
source§

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

Write ASN.1 DER-encoded PKCS#8 private key to the given path
source§

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

Write ASN.1 DER-encoded PKCS#8 private key to the given path
source§

impl<D> From<RsaPrivateKey> for SigningKey<D>
where D: Digest,

source§

fn from(key: RsaPrivateKey) -> SigningKey<D>

Converts to this type from the input type.
source§

impl JWKeyType for SigningKey<Sha256>

source§

const KEY_TYPE: &'static str = "RSA"

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

impl JWKeyType for SigningKey<Sha512>

source§

const KEY_TYPE: &'static str = "RSA"

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

impl JWKeyType for SigningKey<Sha384>

source§

const KEY_TYPE: &'static str = "RSA"

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

impl JoseAlgorithm for SigningKey<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 SigningKey<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 SigningKey<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 SigningKey<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 SigningKey<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 SigningKey<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> Keypair for SigningKey<D>
where D: Digest,

§

type VerifyingKey = VerifyingKey<D>

Verifying key type for this keypair.
source§

fn verifying_key(&self) -> <SigningKey<D> as Keypair>::VerifyingKey

Get the verifying key which can verify signatures produced by the signing key portion of this keypair.
source§

impl<D> PrehashSigner<Signature> for SigningKey<D>
where D: Digest,

source§

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

Attempt to sign the given message digest, returning a digital signature on success, or an error if something went wrong. Read more
source§

impl<D> RandomizedDigestSigner<D, Signature> for SigningKey<D>
where D: Digest,

source§

fn try_sign_digest_with_rng( &self, rng: &mut impl CryptoRngCore, digest: D ) -> Result<Signature, Error>

Attempt to sign the given prehashed message Digest, returning a digital signature on success, or an error if something went wrong.
source§

fn sign_digest_with_rng(&self, rng: &mut impl CryptoRngCore, digest: D) -> S

Sign the given prehashed message Digest, returning a signature. Read more
source§

impl<D> RandomizedSigner<Signature> for SigningKey<D>
where D: Digest,

source§

fn try_sign_with_rng( &self, rng: &mut impl CryptoRngCore, msg: &[u8] ) -> Result<Signature, Error>

Attempt to sign the given message, returning a digital signature on success, or an error if something went wrong. Read more
source§

fn sign_with_rng(&self, rng: &mut impl CryptoRngCore, msg: &[u8]) -> S

Sign the given message and return a digital signature
source§

impl SerializeJWK for SigningKey<Sha256>

source§

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

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

impl SerializeJWK for SigningKey<Sha512>

source§

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

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

impl SerializeJWK for SigningKey<Sha384>

source§

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

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

impl<D> SignatureAlgorithmIdentifier for SigningKey<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> Signer<Signature> for SigningKey<D>
where D: Digest,

source§

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

Attempt to sign the given message, returning a digital signature on success, or an error if something went wrong. Read more
source§

fn sign(&self, msg: &[u8]) -> S

Sign the given message and return a digital signature
source§

impl<D> TryFrom<PrivateKeyInfo<'_>> for SigningKey<D>
where D: Digest + AssociatedOid,

§

type Error = Error

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

fn try_from( private_key_info: PrivateKeyInfo<'_> ) -> Result<SigningKey<D>, Error>

Performs the conversion.
source§

impl<D> ZeroizeOnDrop for SigningKey<D>
where D: Digest,

Auto Trait Implementations§

§

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

§

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

§

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

§

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

§

impl<D> UnwindSafe for SigningKey<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> DecodeEcPrivateKey for T
where T: for<'a> TryFrom<PrivateKeyInfo<'a>, Error = Error>,

§

fn from_sec1_der(private_key: &[u8]) -> Result<T, Error>

Deserialize SEC1 private key from ASN.1 DER-encoded data (binary format).
§

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

Deserialize SEC1-encoded private key from PEM. Read more
§

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

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

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

Load SEC1 private key from a PEM-encoded file on the local filesystem.
source§

impl<T> DecodePrivateKey for T
where T: for<'a> TryFrom<PrivateKeyInfo<'a>, Error = Error>,

source§

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

Deserialize PKCS#8 private key from ASN.1 DER-encoded data (binary format).
source§

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

Deserialize PKCS#8-encoded private key from PEM. Read more
source§

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

Load PKCS#8 private key from an ASN.1 DER-encoded file on the local filesystem (binary format).
source§

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

Load PKCS#8 private key from a PEM-encoded file on the local filesystem.
§

impl<T> DecodeRsaPrivateKey for T
where T: for<'a> TryFrom<PrivateKeyInfo<'a>, Error = Error>,

§

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

Deserialize PKCS#1 private key from ASN.1 DER-encoded data (binary format).
§

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

Deserialize PKCS#1-encoded private key from PEM. Read more
§

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

Load PKCS#1 private key 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 PKCS#1 private key 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> EncodeEcPrivateKey for T

§

fn to_sec1_der(&self) -> Result<SecretDocument, Error>

Serialize a [SecretDocument] containing a SEC1-encoded private key.
§

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

Serialize this private key as PEM-encoded SEC1 with the given LineEnding. Read more
§

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

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

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

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

impl<T> EncodeRsaPrivateKey for T

§

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

Serialize a [SecretDocument] containing a PKCS#1-encoded private key.
§

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

Serialize this private key as PEM-encoded PKCS#1 with the given LineEnding.
§

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

Write ASN.1 DER-encoded PKCS#1 private 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 PKCS#1 private 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<S, T> SignerMut<S> for T
where T: Signer<S>,

source§

fn try_sign(&mut self, msg: &[u8]) -> Result<S, Error>

Attempt to sign the given message, updating the state, and returning a digital signature on success, or an error if something went wrong. Read more
source§

fn sign(&mut self, msg: &[u8]) -> S

Sign the given message, update the state, and return a digital signature.
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