Software APIs
otcrypto_export_test.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 <stdbool.h>
6 #include <stdint.h>
7 #include <string.h>
8 
9 #include "otcrypto.h"
10 #include "sw/device/lib/testing/test_framework/ottf_test_config.h"
11 
12 // This test checks that the static-linked `otcrypto` library is usable and that
13 // the otcrypto include files can stand on their own outside the repository.
14 //
15 // Because we are trying to test the functionality of the includes outside the
16 // repo, we link with the special `crypto_exported_for_test` target and avoid
17 // in-repo definitions of `status_t` and other in-repo macro definitions.
18 
19 // From: http://www.abrahamlincolnonline.org/lincoln/speeches/gettysburg.htm
20 static const char kGettysburgPrelude[] =
21  "Four score and seven years ago our fathers brought forth on this "
22  "continent, a new nation, conceived in Liberty, and dedicated to the "
23  "proposition that all men are created equal.";
24 
25 // The following shell command will produce the sha256sum and convert the
26 // digest into valid C hexadecimal constants:
27 //
28 // $ echo -n "Four score and seven years ago our fathers brought forth on this
29 // continent, a new nation, conceived in Liberty, and dedicated to the
30 // proposition that all men are created equal." |
31 // sha256sum - | cut -f1 -d' ' | sed -e "s/../0x&, /g"
32 //
33 static const uint8_t kGettysburgDigest[] = {
34  0x1e, 0x6f, 0xd4, 0x03, 0x0f, 0x90, 0x34, 0xcd, 0x77, 0x57, 0x08,
35  0xa3, 0x96, 0xc3, 0x24, 0xed, 0x42, 0x0e, 0xc5, 0x87, 0xeb, 0x3d,
36  0xd4, 0x33, 0xe2, 0x9f, 0x6a, 0xc0, 0x8b, 0x8c, 0xc7, 0xba,
37 };
38 
39 enum {
40  kHashLength = 8,
41 };
42 
43 // Check the value of the status_t. If the MSB is set, the value is an
44 // error and we return the error value.
45 #define RETURN_IF_ERROR(expr_) \
46  do { \
47  status_t e = expr_; \
48  if (e.value < 0) \
49  return e.value; \
50  } while (0)
51 
52 int32_t hash_test(void) {
53  uint32_t digest_content[kHashLength];
55  otcrypto_hash_digest_t digest = {
56  .mode = kOtcryptoHashModeSha256,
57  .len = kHashLength,
58  .data = digest_content,
59  };
61  .len = sizeof(kGettysburgPrelude) - 1,
62  .data = (const uint8_t *)kGettysburgPrelude,
63  };
64 
65  RETURN_IF_ERROR(otcrypto_hash_init(&ctx, kOtcryptoHashModeSha256));
66  RETURN_IF_ERROR(otcrypto_hash_update(&ctx, buf));
67  RETURN_IF_ERROR(otcrypto_hash_final(&ctx, digest));
68 
69  if (memcmp(digest.data, kGettysburgDigest, sizeof(kGettysburgDigest)) != 0) {
70  return -1;
71  }
72  return 0;
73 }
74 
75 OTTF_DEFINE_TEST_CONFIG();
76 
77 bool test_main(void) {
78  int result = hash_test();
79  return result == 0;
80 }