script_webcrypto/subtlecrypto/
rsa_oaep_operation.rs1use 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
26pub(crate) fn encrypt<D: Equivalence>(
28 normalized_algorithm: &RsaOaepParams,
29 key: &CryptoKey<D>,
30 plaintext: &[u8],
31) -> Result<Vec<u8>, Error> {
32 key.ensure_type(KeyType::Public)?;
35
36 let label = normalized_algorithm.label.as_deref().unwrap_or_default();
39
40 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 Ok(ciphertext)
86}
87
88pub(crate) fn decrypt<D: Equivalence>(
90 normalized_algorithm: &RsaOaepParams,
91 key: &CryptoKey<D>,
92 ciphertext: &[u8],
93) -> Result<Vec<u8>, Error> {
94 key.ensure_type(KeyType::Private)?;
97
98 let label = normalized_algorithm.label.as_deref().unwrap_or_default();
101
102 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 Ok(plaintext)
150}
151
152pub(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
170pub(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
192pub(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
200pub(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}