Skip to main content

script_webcrypto/subtlecrypto/
hmac_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 hkdf::hmac::Mac;
6use hkdf::{HmacImpl, hmac};
7use js::context::JSContext;
8use rand::TryRng;
9use rand::rngs::SysRng;
10use script_bindings::codegen::GenericBindings::CryptoKeyBinding::{
11    CryptoKeyMethods, KeyType, KeyUsage,
12};
13use script_bindings::codegen::GenericBindings::SubtleCryptoBinding::{JsonWebKey, KeyFormat};
14use script_bindings::domstring::DOMString;
15use script_bindings::error::Error;
16use script_bindings::root::DomRoot;
17use zeroize::Zeroizing;
18
19use crate::cryptokey::{CryptoKey, Handle, KeyUsageSliceHelper};
20use crate::subtlecrypto::{
21    CryptoAlgorithm, ExportedKey, HmacImportParams, HmacKeyAlgorithm, HmacKeyGenParams,
22    JsonWebKeyHelper, JwkStringField, KeyAlgorithmAndDerivatives, NormalizedAlgorithm,
23};
24use crate::traits::Equivalence;
25
26/// <https://w3c.github.io/webcrypto/#hmac-operations-sign>
27pub(crate) fn sign<D: Equivalence>(key: &CryptoKey<D>, message: &[u8]) -> Result<Vec<u8>, Error> {
28    // Step 1. Let mac be the result of performing the HMAC function described in Section 2 of
29    // [NIST-SP800-224] using the key represented by the [[handle]] internal slot of key, the hash
30    // function identified by the hash attribute of the [[algorithm]] internal slot of key and
31    // message as the message M.
32    // Step 2. Return mac.
33    match key.algorithm() {
34        KeyAlgorithmAndDerivatives::HmacKeyAlgorithm(algo) => match algo.hash.name() {
35            CryptoAlgorithm::Sha1 => {
36                let mut hmac =
37                    <hmac::Hmac<sha1::Sha1> as HmacImpl>::new_from_slice(key.handle().as_bytes());
38                HmacImpl::update(&mut hmac, message);
39                Ok(HmacImpl::finalize(hmac).to_vec())
40            },
41            CryptoAlgorithm::Sha256 => {
42                let mut hmac =
43                    <hmac::Hmac<sha2::Sha256> as HmacImpl>::new_from_slice(key.handle().as_bytes());
44                HmacImpl::update(&mut hmac, message);
45                Ok(HmacImpl::finalize(hmac).to_vec())
46            },
47            CryptoAlgorithm::Sha384 => {
48                let mut hmac =
49                    <hmac::Hmac<sha2::Sha384> as HmacImpl>::new_from_slice(key.handle().as_bytes());
50                HmacImpl::update(&mut hmac, message);
51                Ok(HmacImpl::finalize(hmac).to_vec())
52            },
53            CryptoAlgorithm::Sha512 => {
54                let mut hmac =
55                    <hmac::Hmac<sha2::Sha512> as HmacImpl>::new_from_slice(key.handle().as_bytes());
56                HmacImpl::update(&mut hmac, message);
57                Ok(HmacImpl::finalize(hmac).to_vec())
58            },
59            _ => Err(Error::NotSupported(Some(
60                "Unsupported hash algorithm for HMAC".into(),
61            ))),
62        },
63        _ => Err(Error::NotSupported(Some(
64            "The key algorithm is not HMAC".into(),
65        ))),
66    }
67}
68
69/// <https://w3c.github.io/webcrypto/#hmac-operations-verify>
70pub(crate) fn verify<D: Equivalence>(
71    key: &CryptoKey<D>,
72    message: &[u8],
73    signature: &[u8],
74) -> Result<bool, Error> {
75    // Step 1. Let mac be the result of performing the HMAC function described in Section 2 of
76    // [NIST-SP800-224] using the key represented by the [[handle]] internal slot of key, the hash
77    // function identified by the hash attribute of the [[algorithm]] internal slot of key and
78    // message as the message M.
79    // Step 2. Return true if mac is equal to signature and false otherwise. This comparison must
80    // be performed in constant-time.
81    //
82    // NOTE:
83    // [[verify_slice]] performs the comparison in constant time.
84    match key.algorithm() {
85        KeyAlgorithmAndDerivatives::HmacKeyAlgorithm(algo) => match algo.hash.name() {
86            CryptoAlgorithm::Sha1 => {
87                let mut hmac =
88                    <hmac::Hmac<sha1::Sha1> as HmacImpl>::new_from_slice(key.handle().as_bytes());
89                HmacImpl::update(&mut hmac, message);
90                Ok(hmac.verify_slice(signature).is_ok())
91            },
92            CryptoAlgorithm::Sha256 => {
93                let mut hmac =
94                    <hmac::Hmac<sha2::Sha256> as HmacImpl>::new_from_slice(key.handle().as_bytes());
95                HmacImpl::update(&mut hmac, message);
96                Ok(hmac.verify_slice(signature).is_ok())
97            },
98            CryptoAlgorithm::Sha384 => {
99                let mut hmac =
100                    <hmac::Hmac<sha2::Sha384> as HmacImpl>::new_from_slice(key.handle().as_bytes());
101                HmacImpl::update(&mut hmac, message);
102                Ok(hmac.verify_slice(signature).is_ok())
103            },
104            CryptoAlgorithm::Sha512 => {
105                let mut hmac =
106                    <hmac::Hmac<sha2::Sha512> as HmacImpl>::new_from_slice(key.handle().as_bytes());
107                HmacImpl::update(&mut hmac, message);
108                Ok(hmac.verify_slice(signature).is_ok())
109            },
110            _ => Err(Error::NotSupported(Some(
111                "Unsupported hash algorithm for HMAC".into(),
112            ))),
113        },
114        _ => Err(Error::NotSupported(Some(
115            "The key algorithm is not HMAC".into(),
116        ))),
117    }
118}
119
120/// <https://w3c.github.io/webcrypto/#hmac-operations-generate-key>
121pub(crate) fn generate_key<D: Equivalence>(
122    cx: &mut JSContext,
123    global: &D::GlobalScope,
124    normalized_algorithm: &HmacKeyGenParams,
125    extractable: bool,
126    usages: Vec<KeyUsage>,
127) -> Result<DomRoot<CryptoKey<D>>, Error> {
128    // Step 1. If usages contains any entry which is not "sign" or "verify", then throw a
129    // SyntaxError.
130    usages.ensure_only_contain_entries_from(&[KeyUsage::Sign, KeyUsage::Verify])?;
131
132    // Step 2.
133    // If the length member of normalizedAlgorithm is not present:
134    //     Let length be the block size in bits of the hash function identified by the hash member
135    //     of normalizedAlgorithm as specified by Table 2 of [NIST-SP800-224], or 512 for SHA-1.
136    // Otherwise, if the length member of normalizedAlgorithm is non-zero:
137    //     Let length be equal to the length member of normalizedAlgorithm.
138    // Otherwise:
139    //     throw an OperationError.
140    let length = match normalized_algorithm.length {
141        None => hash_function_block_size_in_bits(normalized_algorithm.hash.name())?,
142        Some(length) if length != 0 => length,
143        _ => {
144            return Err(Error::Operation(Some(
145                "The length member of normalizedAlgorithm is zero".into(),
146            )));
147        },
148    };
149
150    // Step 3. Generate a key of length length bits.
151    // Step 4. If the key generation step fails, then throw an OperationError.
152    let mut key_data = vec![0; length as usize];
153    if SysRng.try_fill_bytes(&mut key_data).is_err() {
154        return Err(Error::JSFailed);
155    }
156
157    // Step 6. Let algorithm be a new HmacKeyAlgorithm.
158    // Step 7. Set the name attribute of algorithm to "HMAC".
159    // Step 8. Set the length attribute of algorithm to length.
160    // Step 9. Let hash be a new KeyAlgorithm.
161    // Step 10. Set the name attribute of hash to equal the name member of the hash member of
162    // normalizedAlgorithm.
163    // Step 11. Set the hash attribute of algorithm to hash.
164    let algorithm = HmacKeyAlgorithm {
165        name: CryptoAlgorithm::Hmac,
166        hash: normalized_algorithm.hash.clone(),
167        length,
168    };
169
170    // Step 5. Let key be a new CryptoKey object representing the generated key.
171    // Step 12. Set the [[type]] internal slot of key to "secret".
172    // Step 13. Set the [[algorithm]] internal slot of key to algorithm.
173    // Step 14. Set the [[extractable]] internal slot of key to be extractable.
174    // Step 15. Set the [[usages]] internal slot of key to be the normalized value of usages.
175    let key = CryptoKey::new(
176        cx,
177        global,
178        KeyType::Secret,
179        extractable,
180        KeyAlgorithmAndDerivatives::HmacKeyAlgorithm(algorithm),
181        usages.normalized_value(),
182        Handle::Hmac(key_data.into()),
183    );
184
185    // Step 16. Return key.
186    Ok(key)
187}
188
189/// <https://w3c.github.io/webcrypto/#hmac-operations-import-key>
190pub(crate) fn import_key<D: Equivalence>(
191    cx: &mut JSContext,
192    global: &D::GlobalScope,
193    normalized_algorithm: &HmacImportParams,
194    format: KeyFormat,
195    key_data: &[u8],
196    extractable: bool,
197    usages: Vec<KeyUsage>,
198) -> Result<DomRoot<CryptoKey<D>>, Error> {
199    // Step 1. If the length member of normalizedAlgorithm is present and is zero, then throw a
200    // DataError.
201    if normalized_algorithm
202        .length
203        .is_some_and(|length| length == 0)
204    {
205        return Err(Error::Data(Some(
206            "The length member of normalizedAlgorithm is present and is zero".into(),
207        )));
208    }
209
210    // Step 2. Let keyData be the key data to be imported.
211
212    // Step 3. If usages contains an entry which is not "sign" or "verify", then throw a SyntaxError.
213    usages.ensure_only_contain_entries_from(&[KeyUsage::Sign, KeyUsage::Verify])?;
214
215    // Step 4. Let hash be a new KeyAlgorithm.
216    let hash;
217
218    // Step 5.
219    let data: Zeroizing<Vec<u8>>;
220    match format {
221        // If format is "raw":
222        KeyFormat::Raw | KeyFormat::Raw_secret => {
223            // Step 5.1. Let data be keyData.
224            data = key_data.to_vec().into();
225
226            // Step 5.2. Set hash to equal the hash member of normalizedAlgorithm.
227            hash = &normalized_algorithm.hash;
228        },
229        // If format is "jwk":
230        KeyFormat::Jwk => {
231            // Step 5.1. If keyData is a JsonWebKey dictionary: Let jwk equal keyData.
232            // Otherwise: Throw a DataError.
233            // NOTE: Deserialize keyData to JsonWebKey dictionary by running JsonWebKey::parse
234            let jwk = JsonWebKey::parse(cx, key_data)?;
235
236            // Step 5.2. If the kty field of jwk is not "oct", then throw a DataError.
237            if jwk.kty.as_ref().is_none_or(|kty| kty != "oct") {
238                return Err(Error::Data(Some(
239                    "The kty field of jwk is not \"oct\"".into(),
240                )));
241            }
242
243            // Step 5.3. If jwk does not meet the requirements of Section 6.4 of JSON Web
244            // Algorithms [JWA], then throw a DataError.
245            // NOTE: Done by Step 5.4 and 5.6.
246
247            // Step 5.4. Let data be the byte sequence obtained by decoding the k field of jwk.
248            data = jwk.decode_required_string_field(JwkStringField::K)?;
249
250            // Step 5.5. Set the hash to equal the hash member of normalizedAlgorithm.
251            hash = &normalized_algorithm.hash;
252
253            // Step 5.6.
254            match hash.name() {
255                // If the name attribute of hash is "SHA-1":
256                CryptoAlgorithm::Sha1 => {
257                    // If the alg field of jwk is present and is not "HS1", then throw a DataError.
258                    if jwk.alg.as_ref().is_some_and(|alg| alg != "HS1") {
259                        return Err(Error::Data(Some(
260                            "The alg field of jwk is present, and is not \"HS1\"".into(),
261                        )));
262                    }
263                },
264                // If the name attribute of hash is "SHA-256":
265                CryptoAlgorithm::Sha256 => {
266                    // If the alg field of jwk is present and is not "HS256", then throw a DataError.
267                    if jwk.alg.as_ref().is_some_and(|alg| alg != "HS256") {
268                        return Err(Error::Data(Some(
269                            "The alg field of jwk is present, and is not \"HS256\"".into(),
270                        )));
271                    }
272                },
273                // If the name attribute of hash is "SHA-384":
274                CryptoAlgorithm::Sha384 => {
275                    // If the alg field of jwk is present and is not "HS384", then throw a DataError.
276                    if jwk.alg.as_ref().is_some_and(|alg| alg != "HS384") {
277                        return Err(Error::Data(Some(
278                            "The alg field of jwk is present, and is not \"HS384\"".into(),
279                        )));
280                    }
281                },
282                // If the name attribute of hash is "SHA-512":
283                CryptoAlgorithm::Sha512 => {
284                    // If the alg field of jwk is present and is not "HS512", then throw a DataError.
285                    if jwk.alg.as_ref().is_some_and(|alg| alg != "HS512") {
286                        return Err(Error::Data(Some(
287                            "The alg field of jwk is present, and is not \"HS512\"".into(),
288                        )));
289                    }
290                },
291                // Otherwise,
292                _name => {
293                    // if the name attribute of hash is defined in another applicable specification:
294                    // Perform any key import steps defined by other applicable specifications,
295                    // passing format, jwk and hash and obtaining hash
296                    // NOTE: Currently not support applicable specification.
297                    return Err(Error::NotSupported(Some(
298                        "Unsupported hash algorithm".into(),
299                    )));
300                },
301            }
302
303            // Step 5.7. If usages is non-empty and the use field of jwk is present and is not
304            // "sig", then throw a DataError.
305            if !usages.is_empty() && jwk.use_.as_ref().is_some_and(|use_| use_ != "sig") {
306                return Err(Error::Data(Some(
307                    "Usages is non-empty and the use field of jwk is present and is not \"sig\""
308                        .into(),
309                )));
310            }
311
312            // Step 5.8. If the key_ops field of jwk is present, and is invalid according to
313            // the requirements of JSON Web Key [JWK] or does not contain all of the specified
314            // usages values, then throw a DataError.
315            jwk.check_key_ops(&usages)?;
316
317            // Step 5.9. If the ext field of jwk is present and has the value false and
318            // extractable is true, then throw a DataError.
319            if jwk.ext.is_some_and(|ext| !ext) && extractable {
320                return Err(Error::Data(Some(
321                    "The ext field of jwk is present and has the value false and extractable is true"
322                        .into(),
323                )));
324            }
325        },
326        // Otherwise:
327        _ => {
328            // throw a NotSupportedError.
329            return Err(Error::NotSupported(Some(
330                "Unsupported import key format for HMAC key".into(),
331            )));
332        },
333    }
334
335    // Step 6. Let length be the length in bits of data.
336    let mut length = data.len() as u32 * 8;
337
338    // Step 7. If length is zero then throw a DataError.
339    if length == 0 {
340        return Err(Error::Data(Some(
341            "The length in bits of data is zero".into(),
342        )));
343    }
344
345    // Step 8. If the length member of normalizedAlgorithm is present:
346    if let Some(given_length) = normalized_algorithm.length {
347        //  If the length member of normalizedAlgorithm is greater than length:
348        if given_length > length {
349            // throw a DataError.
350            return Err(Error::Data(Some(
351                "The length member of normalizedAlgorithm is greater than the length in bits of data"
352                    .into(),
353            )));
354        }
355        // Otherwise:
356        else {
357            // Set length equal to the length member of normalizedAlgorithm.
358            length = given_length;
359        }
360    }
361
362    // Step 9. Let key be a new CryptoKey object representing an HMAC key with the first length
363    // bits of data.
364    // Step 10. Set the [[type]] internal slot of key to "secret".
365    // Step 11. Let algorithm be a new HmacKeyAlgorithm.
366    // Step 12. Set the name attribute of algorithm to "HMAC".
367    // Step 13. Set the length attribute of algorithm to length.
368    // Step 14. Set the hash attribute of algorithm to hash.
369    // Step 15. Set the [[algorithm]] internal slot of key to algorithm.
370    let algorithm = HmacKeyAlgorithm {
371        name: CryptoAlgorithm::Hmac,
372        hash: hash.clone(),
373        length,
374    };
375    let truncated_data = data[..length as usize / 8].to_vec();
376    let key = CryptoKey::new(
377        cx,
378        global,
379        KeyType::Secret,
380        extractable,
381        KeyAlgorithmAndDerivatives::HmacKeyAlgorithm(algorithm),
382        usages.normalized_value(),
383        Handle::Hmac(truncated_data.into()),
384    );
385
386    // Step 16. Return key.
387    Ok(key)
388}
389
390/// <https://w3c.github.io/webcrypto/#hmac-operations-export-key>
391pub(crate) fn export_key<D: Equivalence>(
392    format: KeyFormat,
393    key: &CryptoKey<D>,
394) -> Result<ExportedKey, Error> {
395    match format {
396        KeyFormat::Raw | KeyFormat::Raw_secret => match key.handle() {
397            Handle::Hmac(key_data) => Ok(ExportedKey::new_bytes(key_data.as_slice().to_vec())),
398            _ => Err(Error::Operation(Some(
399                "The key handle is not representing an HMAC key".into(),
400            ))),
401        },
402        KeyFormat::Jwk => {
403            // Step 4.1. Let jwk be a new JsonWebKey dictionary.
404            let mut jwk = JsonWebKey::default();
405
406            // Step 4.2. Set the kty attribute of jwk to the string "oct".
407            jwk.kty = Some(DOMString::from_static("oct"));
408
409            // Step 4.3. Set the k attribute of jwk to be a string containing data, encoded according
410            // to Section 6.4 of JSON Web Algorithms [JWA].
411            let key_data = key.handle().as_bytes();
412            jwk.encode_string_field(JwkStringField::K, key_data);
413
414            // Step 4.4. Let algorithm be the [[algorithm]] internal slot of key.
415            // Step 4.5. Let hash be the hash attribute of algorithm.
416            // Step 4.6.
417            // If the name attribute of hash is "SHA-1":
418            //     Set the alg attribute of jwk to the string "HS1".
419            // If the name attribute of hash is "SHA-256":
420            //     Set the alg attribute of jwk to the string "HS256".
421            // If the name attribute of hash is "SHA-384":
422            //     Set the alg attribute of jwk to the string "HS384".
423            // If the name attribute of hash is "SHA-512":
424            //     Set the alg attribute of jwk to the string "HS512".
425            // Otherwise, the name attribute of hash is defined in another applicable
426            // specification:
427            //     Perform any key export steps defined by other applicable specifications, passing
428            //     format and key and obtaining alg.
429            //     Set the alg attribute of jwk to alg.
430            let hash_algorithm = match key.algorithm() {
431                KeyAlgorithmAndDerivatives::HmacKeyAlgorithm(algorithm) => {
432                    match algorithm.hash.name() {
433                        CryptoAlgorithm::Sha1 => "HS1",
434                        CryptoAlgorithm::Sha256 => "HS256",
435                        CryptoAlgorithm::Sha384 => "HS384",
436                        CryptoAlgorithm::Sha512 => "HS512",
437                        _ => {
438                            return Err(Error::NotSupported(Some(
439                                "Unsupported hash algorithm for HMAC".into(),
440                            )));
441                        },
442                    }
443                },
444                _ => {
445                    return Err(Error::NotSupported(Some(
446                        "The key algorithm is not HMAC".into(),
447                    )));
448                },
449            };
450            jwk.alg = Some(DOMString::from(hash_algorithm));
451
452            // Step 4.7. Set the key_ops attribute of jwk to the usages attribute of key.
453            jwk.set_key_ops(key.usages());
454
455            // Step 4.8. Set the ext attribute of jwk to the [[extractable]] internal slot of key.
456            jwk.ext = Some(key.Extractable());
457
458            // Step 4.9. Let result be jwk.
459            Ok(ExportedKey::new_jwk(jwk))
460        },
461        // Otherwise:
462        _ => {
463            // throw a NotSupportedError.
464            Err(Error::NotSupported(Some(
465                "Unsupported export key format for HMAC key".into(),
466            )))
467        },
468    }
469}
470
471/// <https://w3c.github.io/webcrypto/#hmac-operations-get-key-length>
472pub(crate) fn get_key_length(
473    normalized_derived_key_algorithm: &HmacImportParams,
474) -> Result<Option<u32>, Error> {
475    // Step 1.
476    // If the length member of normalizedAlgorithm is not present:
477    //     Let length be the block size in bits of the hash function identified by the hash member
478    //     of normalizedAlgorithm as specified by Table 2 of [NIST-SP800-224], or 512 for SHA-1.
479    // Otherwise, if the length member of normalizedAlgorithm is non-zero:
480    //     Let length be equal to the length member of normalizedAlgorithm.
481    // Otherwise:
482    //     throw an OperationError.
483    let length = match normalized_derived_key_algorithm.length {
484        None => hash_function_block_size_in_bits(normalized_derived_key_algorithm.hash.name())?,
485        Some(length) if length != 0 => length,
486        _ => {
487            return Err(Error::Operation(Some(
488                "The length member of normalizedAlgorithm is zero".into(),
489            )));
490        },
491    };
492
493    // Step 2. Return length.
494    Ok(Some(length))
495}
496
497/// Return the block size in bits of the hash function as specified by Table 2 of [NIST-SP800-224],
498/// or 512 for SHA-1.
499/// <https://nvlpubs.nist.gov/nistpubs/SpecialPublications/NIST.SP.800-224.ipd.pdf>
500fn hash_function_block_size_in_bits(hash: CryptoAlgorithm) -> Result<u32, Error> {
501    match hash {
502        CryptoAlgorithm::Sha1 => Ok(512),
503        CryptoAlgorithm::Sha256 => Ok(512),
504        CryptoAlgorithm::Sha384 => Ok(1024),
505        CryptoAlgorithm::Sha512 => Ok(1024),
506        _ => Err(Error::NotSupported(Some("Unidentified hash member".into()))),
507    }
508}