script_webcrypto/subtlecrypto/kmac_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 cshake::CShake;
6use cshake::digest::{ExtendableOutput, Update};
7use ctutils::CtEq;
8use js::context::JSContext;
9use rand::TryRng;
10use script_bindings::codegen::GenericBindings::CryptoKeyBinding::{
11 CryptoKeyMethods, KeyType, KeyUsage,
12};
13use script_bindings::codegen::GenericBindings::SubtleCryptoBinding::{JsonWebKey, KeyFormat};
14use script_bindings::error::Error;
15use script_bindings::root::DomRoot;
16use script_bindings::str::DOMString;
17use zeroize::Zeroizing;
18
19use crate::cryptokey::{CryptoKey, Handle, KeyUsageSliceHelper};
20use crate::subtlecrypto::{
21 CryptoAlgorithm, ExportedKey, JsonWebKeyHelper, JwkStringField, KeyAlgorithmAndDerivatives,
22 KmacImportParams, KmacKeyAlgorithm, KmacKeyGenParams, KmacParams, truncate_keccak_bit_string,
23};
24use crate::traits::Equivalence;
25
26/// <https://wicg.github.io/webcrypto-modern-algos/#kmac-operations-sign>
27pub(crate) fn sign<D: Equivalence>(
28 normalized_algorithm: &KmacParams,
29 key: &CryptoKey<D>,
30 message: &[u8],
31) -> Result<Vec<u8>, Error> {
32 // Step 1. Let customization be the Keccak decoding of the customization member of
33 // normalizedAlgorithm if present, or the empty bit string otherwise.
34 let customization = normalized_algorithm
35 .customization
36 .as_deref()
37 .unwrap_or_default();
38
39 // Step 2.
40 // If the name member of normalizedAlgorithm is a case-sensitive string match for "KMAC128":
41 // Let mac be the result of performing the KMAC128 function defined in Section 4 of
42 // [NIST-SP800-185] using the raw bits of the key represented by the [[handle]] internal
43 // slot of key as the K input parameter, the Keccak decoding of message as the X input
44 // parameter, the outputLength member of normalizedAlgorithm as the L input parameter, and
45 // customization as the S input parameter.
46 // If the name member of normalizedAlgorithm is a case-sensitive string match for "KMAC256":
47 // Let mac be the result of performing the KMAC256 function defined in Section 4 of
48 // [NIST-SP800-185] using the raw bits of the key represented by the [[handle]] internal
49 // slot of key as the K input parameter, the Keccak decoding of message as the X input
50 // parameter, the outputLength member of normalizedAlgorithm as the L input parameter, and
51 // customization as the S input parameter.
52 // Step 3. If performing the operation results in an error, then throw an OperationError.
53 let Handle::KmacKey(kmac_key) = key.handle() else {
54 return Err(Error::Operation(Some(
55 "[[handle]] internal slot of key is not a KMAC key".into(),
56 )));
57 };
58 let KeyAlgorithmAndDerivatives::KmacKeyAlgorithm(algorithm) = key.algorithm() else {
59 return Err(Error::Operation(Some(
60 "[[algorithm]] internal slot of key is not a KmacKeyAlgorithm".into(),
61 )));
62 };
63 let mac = match normalized_algorithm.name {
64 CryptoAlgorithm::Kmac128 => kmac128(
65 kmac_key,
66 algorithm.length,
67 message,
68 normalized_algorithm.output_length,
69 customization,
70 ),
71 CryptoAlgorithm::Kmac256 => kmac256(
72 kmac_key,
73 algorithm.length,
74 message,
75 normalized_algorithm.output_length,
76 customization,
77 ),
78 algorithm_name => {
79 return Err(Error::NotSupported(Some(format!(
80 "{} is not supported",
81 algorithm_name.as_str()
82 ))));
83 },
84 };
85
86 // Step 4. Return the Keccak encoding of mac.
87 Ok(mac)
88}
89
90/// <https://wicg.github.io/webcrypto-modern-algos/#kmac-operations-verify>
91pub(crate) fn verify<D: Equivalence>(
92 normalized_algorithm: &KmacParams,
93 key: &CryptoKey<D>,
94 message: &[u8],
95 signature: &[u8],
96) -> Result<bool, Error> {
97 // Step 1. Let customization be the Keccak decoding of the customization member of
98 // normalizedAlgorithm if present, or the empty bit string otherwise.
99 let customization = normalized_algorithm
100 .customization
101 .as_deref()
102 .unwrap_or_default();
103
104 // Step 2.
105 // If the name member of normalizedAlgorithm is a case-sensitive string match for "KMAC128":
106 // Let mac be the result of performing the KMAC128 function defined in Section 4 of
107 // [NIST-SP800-185] using the raw bits of the key represented by the [[handle]] internal
108 // slot of key as the K input parameter, the Keccak decoding of message as the X input
109 // parameter, the outputLength member of normalizedAlgorithm as the L input parameter, and
110 // customization as the S input parameter.
111 // If the name member of normalizedAlgorithm is a case-sensitive string match for "KMAC256":
112 // Let mac be the result of performing the KMAC256 function defined in Section 4 of
113 // [NIST-SP800-185] using the raw bits of the key represented by the [[handle]] internal
114 // slot of key as the K input parameter, the Keccak decoding of message as the X input
115 // parameter, the outputLength member of normalizedAlgorithm as the L input parameter, and
116 // customization as the S input parameter.
117 let Handle::KmacKey(kmac_key) = key.handle() else {
118 return Err(Error::Operation(Some(
119 "[[handle]] internal slot of key is not a KMAC key".into(),
120 )));
121 };
122 let KeyAlgorithmAndDerivatives::KmacKeyAlgorithm(algorithm) = key.algorithm() else {
123 return Err(Error::Operation(Some(
124 "[[algorithm]] internal slot of key is not a KmacKeyAlgorithm".into(),
125 )));
126 };
127 let computed_mac = match normalized_algorithm.name {
128 CryptoAlgorithm::Kmac128 => kmac128(
129 kmac_key,
130 algorithm.length,
131 message,
132 normalized_algorithm.output_length,
133 customization,
134 ),
135 CryptoAlgorithm::Kmac256 => kmac256(
136 kmac_key,
137 algorithm.length,
138 message,
139 normalized_algorithm.output_length,
140 customization,
141 ),
142 algorithm_name => {
143 return Err(Error::NotSupported(Some(format!(
144 "{} is not supported",
145 algorithm_name.as_str()
146 ))));
147 },
148 };
149
150 // Step 4. Return true if computedMac is equal to signature and false otherwise. This comparison
151 // must be performed in constant-time.
152 Ok(computed_mac.ct_eq(signature).into())
153}
154
155/// <https://wicg.github.io/webcrypto-modern-algos/#kmac-operations-generate-key>
156pub(crate) fn generate_key<D: Equivalence>(
157 cx: &mut JSContext,
158 global: &D::GlobalScope,
159 normalized_algorithm: &KmacKeyGenParams,
160 extractable: bool,
161 usages: Vec<KeyUsage>,
162) -> Result<DomRoot<CryptoKey<D>>, Error> {
163 // Step 1. If usages contains an entry which is not "sign" or "verify", then throw a
164 // SyntaxError.
165 usages.ensure_only_contain_entries_from(&[KeyUsage::Sign, KeyUsage::Verify])?;
166
167 // Step 2.
168 // If the length member of normalizedAlgorithm is present:
169 // Let length be equal to the length member of normalizedAlgorithm.
170 // Otherwise, if the name member of normalizedAlgorithm is a case-sensitive string match for
171 // "KMAC128":
172 // Let length be 128.
173 // Otherwise, if the name member of normalizedAlgorithm is a case-sensitive string match for
174 // "KMAC256":
175 // Let length be 256.
176 let length = if let Some(normalized_algorithm_length) = normalized_algorithm.length {
177 normalized_algorithm_length
178 } else if normalized_algorithm.name == CryptoAlgorithm::Kmac128 {
179 128
180 } else if normalized_algorithm.name == CryptoAlgorithm::Kmac256 {
181 256
182 } else {
183 return Err(Error::Data(Some(
184 "Unable to determine the length of KMAC key".into(),
185 )));
186 };
187
188 // Step 3. Generate a key of length length bits.
189 // Step 4. If the key generation step fails, then throw an OperationError.
190 //
191 // NOTE: We store the Keccak encoding of the first length bits of data, in the key.
192 // <https://wicg.github.io/webcrypto-modern-algos/#dfn-keccak-encoding>
193 let mut rng = rand::rng();
194 let mut bits = vec![0u8; length.div_ceil(8) as usize];
195 rng.try_fill_bytes(&mut bits)
196 .map_err(|_| Error::Operation(Some("Failed to generate KMAC key".into())))?;
197 truncate_keccak_bit_string(&mut bits, length as usize);
198
199 // Step 5. Let key be a new CryptoKey object representing the generated key.
200 // Step 6. Set the [[type]] internal slot of key to "secret".
201 // Step 7. Let algorithm be a new KmacKeyAlgorithm.
202 // Step 8. Set the name attribute of algorithm to the name member of normalizedAlgorithm.
203 // Step 9. Set the length attribute of algorithm to length.
204 // Step 10. Set the [[algorithm]] internal slot of key to algorithm.
205 // Step 11. Set the [[extractable]] internal slot of key to be extractable.
206 // Step 12. Set the [[usages]] internal slot of key to be the normalized value of usages.
207 let algorithm = KmacKeyAlgorithm {
208 name: normalized_algorithm.name,
209 length,
210 };
211 let key = CryptoKey::new(
212 cx,
213 global,
214 KeyType::Secret,
215 extractable,
216 KeyAlgorithmAndDerivatives::KmacKeyAlgorithm(algorithm),
217 usages.normalized_value(),
218 Handle::KmacKey(bits.into()),
219 );
220
221 // Step 13. Return key.
222 Ok(key)
223}
224
225/// <https://wicg.github.io/webcrypto-modern-algos/#kmac-operations-import-key>
226pub(crate) fn import_key<D: Equivalence>(
227 cx: &mut JSContext,
228 global: &D::GlobalScope,
229 normalized_algorithm: &KmacImportParams,
230 format: KeyFormat,
231 key_data: &[u8],
232 extractable: bool,
233 usages: Vec<KeyUsage>,
234) -> Result<DomRoot<CryptoKey<D>>, Error> {
235 // Step 1. Let keyData be the key data to be imported.
236 // NOTE: It is given as a method parameter.
237
238 // Step 2. If usages contains an entry which is not "sign" or "verify", then throw a
239 // SyntaxError.
240 usages.ensure_only_contain_entries_from(&[KeyUsage::Sign, KeyUsage::Verify])?;
241
242 // Step 3.
243 let mut data: Zeroizing<Vec<u8>>;
244 match format {
245 // If format is "raw-secret":
246 KeyFormat::Raw_secret => {
247 // Step 3.1. Let data be keyData.
248 data = key_data.to_vec().into();
249 },
250 // If format is "jwk":
251 KeyFormat::Jwk => {
252 // Step 3.1.
253 // If keyData is a JsonWebKey dictionary:
254 // Let jwk equal keyData.
255 // Otherwise:
256 // Throw a DataError.
257 let jwk = JsonWebKey::parse(cx, key_data)?;
258
259 // Step 3.2. If the kty field of jwk is not "oct", then throw a DataError.
260 if jwk.kty.as_ref().is_none_or(|kty| kty != "oct") {
261 return Err(Error::Data(Some(
262 "The kty field of jwk is not \"oct\"".into(),
263 )));
264 }
265
266 // Step 3.3. If jwk does not meet the requirements of Section 6.4 of JSON Web Algorithms
267 // [JWA], then throw a DataError.
268 // Step 3.4. Let data be the byte sequence obtained by decoding the k field of jwk.
269 data = jwk.decode_required_string_field(JwkStringField::K)?;
270
271 // Step 3.4.
272 // If the name member of normalizedAlgorithm is a case-sensitive string match for
273 // "KMAC128":
274 // If the alg field of jwk is present and is not "K128", then throw a DataError.
275 // If the name member of normalizedAlgorithm is a case-sensitive string match for
276 // "KMAC256":
277 // If the alg field of jwk is present and is not "K256", then throw a DataError.
278 if normalized_algorithm.name == CryptoAlgorithm::Kmac128 &&
279 jwk.alg.as_ref().is_some_and(|alg| alg != "K128")
280 {
281 return Err(Error::Data(Some(
282 "The alg field of jwk is present and is not \"K128\"".into(),
283 )));
284 }
285 if normalized_algorithm.name == CryptoAlgorithm::Kmac256 &&
286 jwk.alg.as_ref().is_some_and(|alg| alg != "K256")
287 {
288 return Err(Error::Data(Some(
289 "The alg field of jwk is present and is not \"K256\"".into(),
290 )));
291 }
292
293 // Step 3.6. If usages is non-empty and the use field of jwk is present and is not
294 // "sig", then throw a DataError.
295 if !usages.is_empty() && jwk.use_.as_ref().is_some_and(|use_| use_ != "sig") {
296 return Err(Error::Data(Some(
297 "Usages is non-empty and the use field of jwk is present and is not \
298 equal to \"sig\""
299 .into(),
300 )));
301 }
302
303 // Step 3.7. If the key_ops field of jwk is present, and is invalid according to the
304 // requirements of JSON Web Key [JWK] or does not contain all of the specified usages
305 // values, then throw a DataError.
306 jwk.check_key_ops(&usages)?;
307
308 // Step 3.8. If the ext field of jwk is present and has the value false and extractable
309 // is true, then throw a DataError.
310 if jwk.ext.is_some_and(|ext| !ext) && extractable {
311 return Err(Error::Data(Some(
312 "The ext field of jwk is present and has the value false and extractable \
313 is true"
314 .into(),
315 )));
316 }
317 },
318 // Otherwise:
319 _ => {
320 // throw a NotSupportedError.
321 return Err(Error::NotSupported(Some(
322 "Unsupported import key format for KMAC key".into(),
323 )));
324 },
325 }
326
327 // Step 4. Let length be the length in bits of data.
328 let mut length = data.len() as u32 * 8;
329
330 // Step 5.
331 // If the length member of normalizedAlgorithm is present:
332 // If the length member of normalizedAlgorithm is greater than length:
333 // throw a DataError.
334 // If the length member of normalizedAlgorithm, is less than or equal to length minus eight:
335 // throw a DataError.
336 // Otherwise:
337 // Set length equal to the length member of normalizedAlgorithm.
338 if let Some(normalized_algorithm_length) = normalized_algorithm.length {
339 if normalized_algorithm_length > length {
340 return Err(Error::Data(Some("The key bit string is too short".into())));
341 } else if normalized_algorithm_length + 8 <= length {
342 return Err(Error::Data(Some("The key bit string is too long".into())));
343 } else {
344 length = normalized_algorithm_length;
345 }
346 }
347
348 // Step 6. Let key be a new CryptoKey object representing a KMAC key with the first length bits
349 // of the Keccak decoding of data.
350 // Step 7. Set the [[type]] internal slot of key to "secret".
351 // Step 8. Let algorithm be a new KmacKeyAlgorithm.
352 // Step 9. Set the name attribute of algorithm to the name member of normalizedAlgorithm.
353 // Step 10. Set the length attribute of algorithm to length.
354 // Step 11. Set the [[algorithm]] internal slot of key to algorithm.
355 //
356 // NOTE: We store the Keccak encoding of the first length bits of data, in the key.
357 // <https://wicg.github.io/webcrypto-modern-algos/#dfn-keccak-encoding>
358 truncate_keccak_bit_string(&mut data, length as usize);
359 let algorithm = KmacKeyAlgorithm {
360 name: normalized_algorithm.name,
361 length,
362 };
363 let key = CryptoKey::new(
364 cx,
365 global,
366 KeyType::Secret,
367 extractable,
368 KeyAlgorithmAndDerivatives::KmacKeyAlgorithm(algorithm),
369 usages.normalized_value(),
370 Handle::KmacKey(data),
371 );
372
373 // Step 12. Return key.
374 Ok(key)
375}
376
377/// <https://wicg.github.io/webcrypto-modern-algos/#kmac-operations-export-key>
378pub(crate) fn export_key<D: Equivalence>(
379 format: KeyFormat,
380 key: &CryptoKey<D>,
381) -> Result<ExportedKey, Error> {
382 // Step 1. If the underlying cryptographic key material represented by the [[handle]] internal
383 // slot of key cannot be accessed, then throw an OperationError.
384
385 // Step 2. Let bits be the raw bits of the key represented by [[handle]] internal slot of key.
386 // Step 3. Let data be the Keccak encoding of bits.
387 //
388 // NOTE: We already store the Keccak encoding of bits, in the key.
389 // <https://wicg.github.io/webcrypto-modern-algos/#dfn-keccak-encoding>
390 let Handle::KmacKey(data) = key.handle() else {
391 return Err(Error::Operation(Some(
392 "[[handle]] internal slot of key is not a KMAC key".into(),
393 )));
394 };
395
396 // Step 4.
397 let result = match format {
398 // If format is "raw-secret":
399 KeyFormat::Raw_secret => {
400 // Step 4.1. Let result be data.
401 ExportedKey::new_bytes(data.to_vec())
402 },
403 // If format is "jwk":
404 KeyFormat::Jwk => {
405 // Step 4.1. Let jwk be a new JsonWebKey dictionary.
406 let mut jwk = JsonWebKey::default();
407
408 // Step 4.2. Set the kty attribute of jwk to the string "oct".
409 jwk.kty = Some(DOMString::from_static("oct"));
410
411 // Step 4.3. Set the k attribute of jwk to be a string containing data, encoded
412 // according to Section 6.4 of JSON Web Algorithms [JWA].
413 jwk.encode_string_field(JwkStringField::K, data);
414
415 // Step 4.4. Let keyAlgorithm be the [[algorithm]] internal slot of key.
416 let KeyAlgorithmAndDerivatives::KmacKeyAlgorithm(key_algorithm) = key.algorithm()
417 else {
418 return Err(Error::Operation(Some("The key is not a KMAC key".into())));
419 };
420
421 // Step 4.5.
422 // If the name member of keyAlgorithm is "KMAC128":
423 // Set the alg attribute of jwk to the string "K128".
424 // If the name member of keyAlgorithm is "KMAC256":
425 // Set the alg attribute of jwk to the string "K256".
426 if key_algorithm.name == CryptoAlgorithm::Kmac128 {
427 jwk.alg = Some(DOMString::from_static("K128"));
428 }
429 if key_algorithm.name == CryptoAlgorithm::Kmac256 {
430 jwk.alg = Some(DOMString::from_static("K256"));
431 }
432
433 // Step 4.6. Set the key_ops attribute of jwk to equal the usages attribute of key.
434 jwk.set_key_ops(key.usages());
435
436 // Step 4.7. Set the ext attribute of jwk to equal the [[extractable]] internal slot of
437 // key.
438 jwk.ext = Some(key.Extractable());
439
440 // Step 4.8. Let result be jwk.
441 ExportedKey::new_jwk(jwk)
442 },
443 _ => {
444 // throw a NotSupportedError.
445 return Err(Error::NotSupported(Some(
446 "Unsupported import key format for KMAC".into(),
447 )));
448 },
449 };
450
451 // Step 5. Return result.
452 Ok(result)
453}
454
455/// <https://wicg.github.io/webcrypto-modern-algos/#kmac-operations-get-key-length>
456pub(crate) fn get_key_length(
457 normalized_algorithm: &KmacImportParams,
458) -> Result<Option<u32>, Error> {
459 // Step 1.
460 // If the length member of normalizedAlgorithm is present:
461 // Let length be equal to the length member of normalizedAlgorithm.
462 // Otherwise, if the name member of normalizedAlgorithm is a case-sensitive string match for
463 // "KMAC128":
464 // Let length be 128.
465 // Otherwise, if the name member of normalizedAlgorithm is a case-sensitive string match for
466 // "KMAC256":
467 // Let length be 256.
468 let length = if let Some(normalized_algorithm_length) = normalized_algorithm.length {
469 normalized_algorithm_length
470 } else if normalized_algorithm.name == CryptoAlgorithm::Kmac128 {
471 128
472 } else if normalized_algorithm.name == CryptoAlgorithm::Kmac256 {
473 256
474 } else {
475 return Err(Error::Data(Some(
476 "Unable to determine the length of KMAC key".into(),
477 )));
478 };
479
480 // Step 2. Return length.
481 Ok(Some(length))
482}
483
484/// The KMAC128 function defined in Section 4 of [NIST-SP800-185], using `key` as the K input
485/// parameter, `message` as the X input parameter, `output_length` as the L input parameter, and
486/// `customization` as the S input parameter, where `key_length` is the key length in bits.
487/// <https://nvlpubs.nist.gov/nistpubs/SpecialPublications/NIST.SP.800-185.pdf>
488///
489/// Since the key is represented as a byte sequence, and the key length in bits might not be a
490/// muliple of 8, callers need to provide the actual key length in bits via the function argument
491/// `key_length`, and the excess bits at the end of the byte sequence must be zeros.
492fn kmac128(
493 key: &[u8],
494 key_length: u32,
495 message: &[u8],
496 output_length: u32,
497 customization: &[u8],
498) -> Vec<u8> {
499 kmac::<168>(key, key_length, message, output_length, customization)
500}
501
502/// The KMAC256 function defined in Section 4 of [NIST-SP800-185], using `key` as the K input
503/// parameter, `message` as the X input parameter, `output_length` as the L input parameter, and
504/// `customization` as the S input parameter, where `key_length` is the key length in bits.
505/// <https://nvlpubs.nist.gov/nistpubs/SpecialPublications/NIST.SP.800-185.pdf>
506///
507/// Since the key is represented as a byte sequence, and the key length in bits might not be a
508/// muliple of 8, callers need to provide the actual key length in bits via the function argument
509/// `key_length`, and the excess bits at the end of the byte sequence must be zeros.
510fn kmac256(
511 key: &[u8],
512 key_length: u32,
513 message: &[u8],
514 output_length: u32,
515 customization: &[u8],
516) -> Vec<u8> {
517 kmac::<136>(key, key_length, message, output_length, customization)
518}
519
520/// A shared implementation for both the KMAC128 function and KMAC256 function defined in Section 4
521/// of [NIST-SP800-185], using `key` as the K input parameter, `message` as the X input parameter,
522/// `output_length` as the L input parameter, and `customization` as the S input parameter, where
523/// `key_length` is the key length in bits.
524/// <https://nvlpubs.nist.gov/nistpubs/SpecialPublications/NIST.SP.800-185.pdf>
525///
526/// To be specific, this function implements the following algorithm, where RATE must be either 168
527/// or 136 for KMAC128 and KMAC256 respectively.
528///
529/// 1. newX = bytepad(encode_string(K), RATE) || X || right_encode(L).
530/// 2. return cSHAKE128(newX, L, “KMAC”, S).
531///
532/// Since the key is represented as a byte sequence, and the key length in bits might not be a
533/// muliple of 8, callers need to provide the actual key length in bits via the function argument
534/// `key_length`, and the excess bits at the end of the byte sequence must be zeros.
535fn kmac<const RATE: usize>(
536 key: &[u8],
537 key_length: u32,
538 message: &[u8],
539 output_length: u32,
540 customization: &[u8],
541) -> Vec<u8> {
542 let mut buffer = [0u8; 5];
543 let zeros = [0u8; RATE];
544
545 // Initialize cSHAKE.
546 let mut cshake = CShake::<RATE>::new_with_function_name(b"KMAC", customization);
547
548 // Hash bytepad(encode_string(K), RATE).
549 let update_and_return_written = |cshake: &mut CShake<RATE>, input: &[u8]| -> usize {
550 cshake.update(input);
551 input.len()
552 };
553 let mut written = update_and_return_written(&mut cshake, left_encode(RATE as u32, &mut buffer));
554 written += update_and_return_written(&mut cshake, left_encode(key_length, &mut buffer));
555 written += update_and_return_written(&mut cshake, key);
556 cshake.update(&zeros[0..RATE - written % RATE]);
557
558 // Hash X.
559 cshake.update(message);
560
561 // Hash right_encode(L).
562 cshake.update(right_encode(output_length, &mut buffer));
563
564 // Finalize cSHAKE.
565 let mut result = vec![0u8; output_length.div_ceil(8) as usize];
566 cshake.finalize_xof_into(&mut result);
567 truncate_keccak_bit_string(&mut result, output_length as usize);
568
569 result
570}
571
572/// The right_encode function defined in Section 2.3.1 of [NIST-SP800-185], using `value` as the x
573/// input parameter. <https://nvlpubs.nist.gov/nistpubs/SpecialPublications/NIST.SP.800-185.pdf>
574///
575/// Callers need to provide `buffer` for internal operations. The buffer can be reused afterwards in
576/// separate calls of [`right_encode`] and [`left_encode`].
577fn right_encode(value: u32, buffer: &mut [u8; 5]) -> &[u8] {
578 buffer[0..4].copy_from_slice(&value.to_be_bytes());
579 let leading_zero = buffer[0..3].iter().take_while(|byte| **byte == 0).count();
580 buffer[4] = u8::try_from(4 - leading_zero).expect("The number must be 1..=4");
581 &buffer[leading_zero..5]
582}
583
584/// The left_encode function defined in Section 2.3.1 of [NIST-SP800-185], using `value` as the x
585/// input parameter. <https://nvlpubs.nist.gov/nistpubs/SpecialPublications/NIST.SP.800-185.pdf>
586///
587/// Callers need to provide `buffer` for internal operations. The buffer can be reused afterwards in
588/// separate calls of [`right_encode`] and [`left_encode`].
589fn left_encode(value: u32, buffer: &mut [u8; 5]) -> &[u8] {
590 buffer[1..5].copy_from_slice(&value.to_be_bytes());
591 let leading_zero = buffer[1..4].iter().take_while(|byte| **byte == 0).count();
592 buffer[leading_zero] = u8::try_from(4 - leading_zero).expect("The number must be 1..=4");
593 &buffer[leading_zero..5]
594}