Skip to main content

script_webcrypto/subtlecrypto/
rsa_pss_operation.rs

1/* This Source Code Form is subject to the terms of the Mozilla Public
2 * License, v. 2.0. If a copy of the MPL was not distributed with this
3 * file, You can obtain one at https://mozilla.org/MPL/2.0/. */
4
5use js::context::JSContext;
6use rsa::pss::{Signature, SigningKey, VerifyingKey};
7use rsa::signature::{RandomizedSigner, SignatureEncoding, Verifier};
8use script_bindings::codegen::GenericBindings::CryptoKeyBinding::{
9    CryptoKeyPair, KeyType, KeyUsage,
10};
11use script_bindings::codegen::GenericBindings::SubtleCryptoBinding::KeyFormat;
12use script_bindings::error::Error;
13use script_bindings::root::DomRoot;
14use script_bindings::trace::RootedTraceableBox;
15use sha1::Sha1;
16use sha2::{Sha256, Sha384, Sha512};
17
18use crate::cryptokey::{CryptoKey, Handle};
19use crate::subtlecrypto::rsa_common::{self, RsaAlgorithm};
20use crate::subtlecrypto::{
21    CryptoAlgorithm, ExportedKey, KeyAlgorithmAndDerivatives, NormalizedAlgorithm,
22    RsaHashedImportParams, RsaHashedKeyGenParams, RsaPssParams,
23};
24use crate::traits::Equivalence;
25
26/// <https://w3c.github.io/webcrypto/#rsa-pss-operations-sign>
27pub(crate) fn sign<D: Equivalence>(
28    normalized_algorithm: &RsaPssParams,
29    key: &CryptoKey<D>,
30    message: &[u8],
31) -> Result<Vec<u8>, Error> {
32    // Step 1. If the [[type]] internal slot of key is not "private", then throw an
33    // InvalidAccessError.
34    key.ensure_type(KeyType::Private)?;
35
36    // Step 2. Perform the signature generation operation defined in Section 8.1 of [RFC3447] with
37    // the key represented by the [[handle]] internal slot of key as the signer's private key, K,
38    // and message as the message to be signed, M, and using the hash function specified by the
39    // hash attribute of the [[algorithm]] internal slot of key as the Hash option, MGF1 (defined
40    // in Section B.2.1 of [RFC3447]) as the MGF option and the saltLength member of
41    // normalizedAlgorithm as the salt length option for the EMSA-PSS-ENCODE operation.
42    // Step 3. If performing the operation results in an error, then throw an OperationError.
43    // Step 4. Let signature be the signature, S, that results from performing the operation.
44    let Handle::RsaPrivateKey(private_key) = key.handle() else {
45        return Err(Error::Operation(Some(
46            "[[handle]] internal slot of key is not an RSA private key".to_string(),
47        )));
48    };
49    let KeyAlgorithmAndDerivatives::RsaHashedKeyAlgorithm(algorithm) = key.algorithm() else {
50        return Err(Error::Operation(Some(
51            "[[algorithm]] internal slot of key is not an RsaHashedKeyAlgorithm".to_string(),
52        )));
53    };
54    let mut rng = rand::rng();
55    let signature = match algorithm.hash.name() {
56        CryptoAlgorithm::Sha1 => {
57            let signing_key = SigningKey::<Sha1>::new_with_salt_len(
58                private_key.clone(),
59                normalized_algorithm.salt_length as usize,
60            );
61            signing_key.try_sign_with_rng(&mut rng, message)
62        },
63        CryptoAlgorithm::Sha256 => {
64            let signing_key = SigningKey::<Sha256>::new_with_salt_len(
65                private_key.clone(),
66                normalized_algorithm.salt_length as usize,
67            );
68            signing_key.try_sign_with_rng(&mut rng, message)
69        },
70        CryptoAlgorithm::Sha384 => {
71            let signing_key = SigningKey::<Sha384>::new_with_salt_len(
72                private_key.clone(),
73                normalized_algorithm.salt_length as usize,
74            );
75            signing_key.try_sign_with_rng(&mut rng, message)
76        },
77        CryptoAlgorithm::Sha512 => {
78            let signing_key = SigningKey::<Sha512>::new_with_salt_len(
79                private_key.clone(),
80                normalized_algorithm.salt_length as usize,
81            );
82            signing_key.try_sign_with_rng(&mut rng, message)
83        },
84        _ => {
85            return Err(Error::Operation(Some(format!(
86                "Unsupported \"{}\" hash for RSA-PSS",
87                algorithm.hash.name().as_str()
88            ))));
89        },
90    }
91    .map_err(|_| Error::Operation(Some("RSA-PSS failed to sign message".to_string())))?;
92
93    // Step 5. Return signature.
94    Ok(signature.to_vec())
95}
96
97/// <https://w3c.github.io/webcrypto/#rsa-pss-operations-verify>
98pub(crate) fn verify<D: Equivalence>(
99    normalized_algorithm: &RsaPssParams,
100    key: &CryptoKey<D>,
101    message: &[u8],
102    signature: &[u8],
103) -> Result<bool, Error> {
104    // Step 1. If the [[type]] internal slot of key is not "public", then throw an
105    // InvalidAccessError.
106    key.ensure_type(KeyType::Public)?;
107
108    // Step 2. Perform the signature verification operation defined in Section 8.1 of [RFC3447]
109    // with the key represented by the [[handle]] internal slot of key as the signer's RSA public
110    // key and message as M and signature as S and using the hash function specified by the hash
111    // attribute of the [[algorithm]] internal slot of key as the Hash option, MGF1 (defined in
112    // Section B.2.1 of [RFC3447]) as the MGF option and the saltLength member of
113    // normalizedAlgorithm as the salt length option for the EMSA-PSS-VERIFY operation.
114    // Step 3. Let result be a boolean with the value true if the result of the operation was
115    // "valid signature" and the value false otherwise.
116    let Handle::RsaPublicKey(public_key) = key.handle() else {
117        return Err(Error::Operation(Some(
118            "[[handle]] internal slot of key is not an RSA public key".to_string(),
119        )));
120    };
121    let KeyAlgorithmAndDerivatives::RsaHashedKeyAlgorithm(algorithm) = key.algorithm() else {
122        return Err(Error::Operation(Some(
123            "[[algorithm]] internal slot of key is not an RsaHashedKeyAlgorithm".to_string(),
124        )));
125    };
126    let signature = Signature::try_from(signature)
127        .map_err(|_| Error::Operation(Some("Failed to parse RSA signature".to_string())))?;
128    let result = match algorithm.hash.name() {
129        CryptoAlgorithm::Sha1 => {
130            let verifying_key = VerifyingKey::<Sha1>::new_with_salt_len(
131                public_key.clone(),
132                normalized_algorithm.salt_length as usize,
133            );
134            verifying_key.verify(message, &signature)
135        },
136        CryptoAlgorithm::Sha256 => {
137            let verifying_key = VerifyingKey::<Sha256>::new_with_salt_len(
138                public_key.clone(),
139                normalized_algorithm.salt_length as usize,
140            );
141            verifying_key.verify(message, &signature)
142        },
143        CryptoAlgorithm::Sha384 => {
144            let verifying_key = VerifyingKey::<Sha384>::new_with_salt_len(
145                public_key.clone(),
146                normalized_algorithm.salt_length as usize,
147            );
148            verifying_key.verify(message, &signature)
149        },
150        CryptoAlgorithm::Sha512 => {
151            let verifying_key = VerifyingKey::<Sha512>::new_with_salt_len(
152                public_key.clone(),
153                normalized_algorithm.salt_length as usize,
154            );
155            verifying_key.verify(message, &signature)
156        },
157        _ => {
158            return Err(Error::Operation(Some(format!(
159                "Unsupported \"{}\" hash for RSASSA-PKCS1-v1_5",
160                algorithm.hash.name().as_str()
161            ))));
162        },
163    }
164    .is_ok();
165
166    // Step 4. Return result.
167    Ok(result)
168}
169
170/// <https://w3c.github.io/webcrypto/#rsa-pss-operations-generate-key>
171pub(crate) fn generate_key<D: Equivalence>(
172    cx: &mut JSContext,
173    global: &D::GlobalScope,
174    normalized_algorithm: &RsaHashedKeyGenParams,
175    extractable: bool,
176    usages: Vec<KeyUsage>,
177) -> Result<RootedTraceableBox<CryptoKeyPair<D>>, Error> {
178    rsa_common::generate_key(
179        cx,
180        global,
181        RsaAlgorithm::RsaPss,
182        normalized_algorithm,
183        extractable,
184        usages,
185    )
186}
187
188/// <https://w3c.github.io/webcrypto/#rsa-pss-operations-import-key>
189pub(crate) fn import_key<D: Equivalence>(
190    cx: &mut JSContext,
191    global: &D::GlobalScope,
192    normalized_algorithm: &RsaHashedImportParams,
193    format: KeyFormat,
194    key_data: &[u8],
195    extractable: bool,
196    usages: Vec<KeyUsage>,
197) -> Result<DomRoot<CryptoKey<D>>, Error> {
198    rsa_common::import_key(
199        cx,
200        global,
201        RsaAlgorithm::RsaPss,
202        normalized_algorithm,
203        format,
204        key_data,
205        extractable,
206        usages,
207    )
208}
209
210/// <https://w3c.github.io/webcrypto/#rsa-pss-operations-export-key>
211pub(crate) fn export_key<D: Equivalence>(
212    format: KeyFormat,
213    key: &CryptoKey<D>,
214) -> Result<ExportedKey, Error> {
215    rsa_common::export_key(RsaAlgorithm::RsaPss, format, key)
216}
217
218/// <https://wicg.github.io/webcrypto-modern-algos/#SubtleCrypto-method-getPublicKey>
219/// Step 9 - 15, for RSA-PSS
220pub(crate) fn get_public_key<D: Equivalence>(
221    cx: &mut JSContext,
222    global: &D::GlobalScope,
223    key: &CryptoKey<D>,
224    algorithm: &KeyAlgorithmAndDerivatives,
225    usages: Vec<KeyUsage>,
226) -> Result<DomRoot<CryptoKey<D>>, Error> {
227    rsa_common::get_public_key(cx, global, RsaAlgorithm::RsaPss, key, algorithm, usages)
228}