Software APIs
template.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 #include "sw/device/silicon_creator/lib/cert/template.h"
6 
7 #include <limits.h>
8 
9 static const char kLowercaseHexChars[16] = {'0', '1', '2', '3', '4', '5',
10  '6', '7', '8', '9', 'a', 'b',
11  'c', 'd', 'e', 'f'};
12 
13 uint8_t *template_push_hex_impl(uint8_t *out, const uint8_t *bytes,
14  size_t size) {
15  while (size > 0) {
16  *out++ = (uint8_t)kLowercaseHexChars[bytes[0] >> 4];
17  *out++ = (uint8_t)kLowercaseHexChars[bytes[0] & 0xf];
18  bytes++;
19  size--;
20  }
21  return out;
22 }
23 
24 uint8_t *template_asn1_integer_impl(uint8_t *out, uint8_t tag, bool tweak_msb,
25  const uint8_t *bytes_be, size_t size) {
26  *out++ = tag;
27  uint8_t *size_ptr = out++;
28  if (tweak_msb) {
29  *out++ = 0; // additional zero prefix;
30  } else {
31  while (size > 0 && *bytes_be == 0) {
32  ++bytes_be;
33  --size;
34  }
35  if (size == 0 || *bytes_be > 0x7f) {
36  *out++ = 0;
37  }
38  }
39  memcpy(out, bytes_be, size);
40  if (tweak_msb)
41  out[0] |= 0x80;
42  out += size;
43  *size_ptr = (uint8_t)(out - size_ptr) - 1;
44  return out;
45 }
46 
47 void template_patch_size_be_impl(template_pos_t memo, uint8_t *out_end) {
48  *(uint16_t *)memo = __builtin_bswap16(__builtin_bswap16(*(uint16_t *)memo) +
49  (uint16_t)(out_end - (uint8_t *)memo));
50 }