Skip to main content

script_webcrypto/subtlecrypto/
rsa_oaep_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::oaep::{DecryptingKey, EncryptingKey};
7use rsa::traits::{Decryptor, RandomizedEncryptor};
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, RsaOaepParams,
23};
24use crate::traits::Equivalence;
25
26/// <https://w3c.github.io/webcrypto/#rsa-oaep-operations-encrypt>
27pub(crate) fn encrypt<D: Equivalence>(
28    normalized_algorithm: &RsaOaepParams,
29    key: &CryptoKey<D>,
30    plaintext: &[u8],
31) -> Result<Vec<u8>, Error> {
32    // Step 1. If the [[type]] internal slot of key is not "public", then throw an
33    // InvalidAccessError.
34    key.ensure_type(KeyType::Public)?;
35
36    // Step 2. Let label be the label member of normalizedAlgorithm or the empty byte sequence if
37    // the label member of normalizedAlgorithm is not present.
38    let label = normalized_algorithm.label.as_deref().unwrap_or_default();
39
40    // Step 3. Perform the encryption operation defined in Section 7.1 of [RFC3447] with the key
41    // represented by key as the recipient's RSA public key, plaintext as the message to be
42    // encrypted, M and label as the label, L, and with the hash function specified by the hash
43    // attribute of the [[algorithm]] internal slot of key as the Hash option and MGF1 (defined in
44    // Section B.2.1 of [RFC3447]) as the MGF option.
45    // Step 4. If performing the operation results in an error, then throw an OperationError.
46    // Step 5. Let ciphertext be the value C that results from performing the operation.
47    let Handle::RsaPublicKey(public_key) = key.handle() else {
48        return Err(Error::Operation(Some(
49            "[[handle]] internal slot of key is not an RSA public key".to_string(),
50        )));
51    };
52    let KeyAlgorithmAndDerivatives::RsaHashedKeyAlgorithm(algorithm) = key.algorithm() else {
53        return Err(Error::Operation(Some(
54            "[[algorithm]] internal slot of key is not an RsaHashedKeyAlgorithm".to_string(),
55        )));
56    };
57    let mut rng = rand::rng();
58    let ciphertext = match algorithm.hash.name() {
59        CryptoAlgorithm::Sha1 => {
60            let encryption_key = EncryptingKey::<Sha1>::new_with_label(public_key.clone(), label);
61            encryption_key.encrypt_with_rng(&mut rng, plaintext)
62        },
63        CryptoAlgorithm::Sha256 => {
64            let encryption_key = EncryptingKey::<Sha256>::new_with_label(public_key.clone(), label);
65            encryption_key.encrypt_with_rng(&mut rng, plaintext)
66        },
67        CryptoAlgorithm::Sha384 => {
68            let encryption_key = EncryptingKey::<Sha384>::new_with_label(public_key.clone(), label);
69            encryption_key.encrypt_with_rng(&mut rng, plaintext)
70        },
71        CryptoAlgorithm::Sha512 => {
72            let encryption_key = EncryptingKey::<Sha512>::new_with_label(public_key.clone(), label);
73            encryption_key.encrypt_with_rng(&mut rng, plaintext)
74        },
75        algorithm_hash_name => {
76            return Err(Error::Operation(Some(format!(
77                "Unsupported hash for RSASSA-PKCS1-v1_5: {}",
78                algorithm_hash_name.as_str()
79            ))));
80        },
81    }
82    .map_err(|_| Error::Operation(Some("RSA-OAEP failed to encrypt plaintext".into())))?;
83
84    // Step 6. Return ciphertext.
85    Ok(ciphertext)
86}
87
88/// <https://w3c.github.io/webcrypto/#rsa-oaep-operations-decrypt>
89pub(crate) fn decrypt<D: Equivalence>(
90    normalized_algorithm: &RsaOaepParams,
91    key: &CryptoKey<D>,
92    ciphertext: &[u8],
93) -> Result<Vec<u8>, Error> {
94    // Step 1. If the [[type]] internal slot of key is not "private", then throw an
95    // InvalidAccessError.
96    key.ensure_type(KeyType::Private)?;
97
98    // Step 2. Let label be the label member of normalizedAlgorithm or the empty byte sequence if
99    // the label member of normalizedAlgorithm is not present.
100    let label = normalized_algorithm.label.as_deref().unwrap_or_default();
101
102    // Step 3. Perform the decryption operation defined in Section 7.1 of [RFC3447] with the key
103    // represented by key as the recipient's RSA private key, ciphertext as the ciphertext to be
104    // decrypted, C, and label as the label, L, and with the hash function specified by the hash
105    // attribute of the [[algorithm]] internal slot of key as the Hash option and MGF1 (defined in
106    // Section B.2.1 of [RFC3447]) as the MGF option.
107    // Step 4. If performing the operation results in an error, then throw an OperationError.
108    // Step 5. Let plaintext the value M that results from performing the operation.
109    let Handle::RsaPrivateKey(private_key) = key.handle() else {
110        return Err(Error::Operation(Some(
111            "[[handle]] internal slot of key is not an RSA private key".to_string(),
112        )));
113    };
114    let KeyAlgorithmAndDerivatives::RsaHashedKeyAlgorithm(algorithm) = key.algorithm() else {
115        return Err(Error::Operation(Some(
116            "[[algorithm]] internal slot of key is not an RsaHashedKeyAlgorithm".to_string(),
117        )));
118    };
119    let plaintext = match algorithm.hash.name() {
120        CryptoAlgorithm::Sha1 => {
121            let decrypting_key = DecryptingKey::<Sha1>::new_with_label(private_key.clone(), label);
122            decrypting_key.decrypt(ciphertext)
123        },
124        CryptoAlgorithm::Sha256 => {
125            let decrypting_key =
126                DecryptingKey::<Sha256>::new_with_label(private_key.clone(), label);
127            decrypting_key.decrypt(ciphertext)
128        },
129        CryptoAlgorithm::Sha384 => {
130            let decrypting_key =
131                DecryptingKey::<Sha384>::new_with_label(private_key.clone(), label);
132            decrypting_key.decrypt(ciphertext)
133        },
134        CryptoAlgorithm::Sha512 => {
135            let decrypting_key =
136                DecryptingKey::<Sha512>::new_with_label(private_key.clone(), label);
137            decrypting_key.decrypt(ciphertext)
138        },
139        algorithm_hash_name => {
140            return Err(Error::Operation(Some(format!(
141                "Unsupported hash for RSASSA-PKCS1-v1_5: {}",
142                algorithm_hash_name.as_str()
143            ))));
144        },
145    }
146    .map_err(|_| Error::Operation(Some("RSA-OAEP failed to decrypt ciphertext".into())))?;
147
148    // Step 6. Return plaintext.
149    Ok(plaintext)
150}
151
152/// <https://w3c.github.io/webcrypto/#rsa-oaep-operations-generate-key>
153pub(crate) fn generate_key<D: Equivalence>(
154    cx: &mut JSContext,
155    global: &D::GlobalScope,
156    normalized_algorithm: &RsaHashedKeyGenParams,
157    extractable: bool,
158    usages: Vec<KeyUsage>,
159) -> Result<RootedTraceableBox<CryptoKeyPair<D>>, Error> {
160    rsa_common::generate_key(
161        cx,
162        global,
163        RsaAlgorithm::RsaOaep,
164        normalized_algorithm,
165        extractable,
166        usages,
167    )
168}
169
170/// <https://w3c.github.io/webcrypto/#rsa-oaep-operations-import-key>
171pub(crate) fn import_key<D: Equivalence>(
172    cx: &mut JSContext,
173    global: &D::GlobalScope,
174    normalized_algorithm: &RsaHashedImportParams,
175    format: KeyFormat,
176    key_data: &[u8],
177    extractable: bool,
178    usages: Vec<KeyUsage>,
179) -> Result<DomRoot<CryptoKey<D>>, Error> {
180    rsa_common::import_key(
181        cx,
182        global,
183        RsaAlgorithm::RsaOaep,
184        normalized_algorithm,
185        format,
186        key_data,
187        extractable,
188        usages,
189    )
190}
191
192/// <https://w3c.github.io/webcrypto/#rsa-oaep-operations-export-key>
193pub(crate) fn export_key<D: Equivalence>(
194    format: KeyFormat,
195    key: &CryptoKey<D>,
196) -> Result<ExportedKey, Error> {
197    rsa_common::export_key(RsaAlgorithm::RsaOaep, format, key)
198}
199
200/// <https://wicg.github.io/webcrypto-modern-algos/#SubtleCrypto-method-getPublicKey>
201/// Step 9 - 15, for RSA-OAEP
202pub(crate) fn get_public_key<D: Equivalence>(
203    cx: &mut JSContext,
204    global: &D::GlobalScope,
205    key: &CryptoKey<D>,
206    algorithm: &KeyAlgorithmAndDerivatives,
207    usages: Vec<KeyUsage>,
208) -> Result<DomRoot<CryptoKey<D>>, Error> {
209    rsa_common::get_public_key(cx, global, RsaAlgorithm::RsaOaep, key, algorithm, usages)
210}