Software APIs
sha2.c
1 // Copyright lowRISC contributors (OpenTitan project).
2 // Licensed under the Apache License, Version 2.0, see LICENSE for details.
3 // SPDX-License-Identifier: Apache-2.0
4 //
5 // Derived from code in the SPHINCS+ reference implementation (CC0 license):
6 // https://github.com/sphincs/sphincsplus/blob/7ec789ace6874d875f4bb84cb61b81155398167e/ref/sha2.c
7 
9 #include "sw/device/silicon_creator/lib/drivers/hmac.h"
10 
11 void mgf1_sha256(const uint32_t *in, size_t in_len, size_t out_len,
12  uint32_t *out) {
13  // Append SHA256(in || counter) to the output until the requested length is
14  // reached.
15  for (uint32_t ctr = 0; ctr * kHmacDigestNumWords < out_len; ctr++) {
16  hmac_sha256_start();
17  hmac_sha256_update_words(in, in_len);
18  uint32_t ctr_be = __builtin_bswap32(ctr);
19  hmac_sha256_update_words(&ctr_be, 1);
20  hmac_sha256_process();
21  // If the remaining output needed is less than the full digest size,
22  // truncate.
23  size_t digest_words =
24  (out_len <= kHmacDigestNumWords) ? out_len : kHmacDigestNumWords;
25  hmac_sha256_final_truncated(out, digest_words);
26  out += digest_words;
27  }
28 }