RTEMS
t-test-hash-sha256.c
1 /*
2  * SPDX-License-Identifier: BSD-2-Clause
3  *
4  * Copyright (C) 2019 embedded brains GmbH
5  *
6  * Redistribution and use in source and binary forms, with or without
7  * modification, are permitted provided that the following conditions
8  * are met:
9  * 1. Redistributions of source code must retain the above copyright
10  * notice, this list of conditions and the following disclaimer.
11  * 2. Redistributions in binary form must reproduce the above copyright
12  * notice, this list of conditions and the following disclaimer in the
13  * documentation and/or other materials provided with the distribution.
14  *
15  * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
16  * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
17  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
18  * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
19  * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
20  * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
21  * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
22  * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
23  * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
24  * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
25  * POSSIBILITY OF SUCH DAMAGE.
26  */
27 
28 #include <rtems/test.h>
29 
30 #if defined(__rtems__)
31 #include <sha256.h>
32 #else
33 #include <openssl/sha.h>
34 #endif
35 
36 typedef struct {
37  SHA256_CTX sha256;
38  T_putchar putchar;
39  void *putchar_arg;
41 
42 static T_report_hash_sha256_context T_report_hash_sha256_instance;
43 
44 static void
45 T_report_hash_sha256_putchar(int c, void *arg)
46 {
48  char cc;
49 
50  ctx = arg;
51  cc = (char)c;
52  SHA256_Update(&ctx->sha256, &cc, sizeof(cc));
53  (*ctx->putchar)(c, ctx->putchar_arg);
54 }
55 
56 static void
57 T_report_hash_sha256_initialize(void)
58 {
60 
61  ctx = &T_report_hash_sha256_instance;
62  SHA256_Init(&ctx->sha256);
63  T_set_putchar(T_report_hash_sha256_putchar, ctx, &ctx->putchar,
64  &ctx->putchar_arg);
65 }
66 
67 static void
68 T_report_hash_sha256_finalize(void)
69 {
71  unsigned char hash[32];
72  size_t i;
73 
74  ctx = &T_report_hash_sha256_instance;
75  SHA256_Final(hash, &ctx->sha256);
76  T_printf("Y:ReportHash:SHA256:");
77 
78  for (i = 0; i < 32; ++i) {
79  T_printf("%02x", hash[i]);
80  }
81 
82  T_printf("\n");
83 }
84 
85 void
86 T_report_hash_sha256(T_event event, const char *name)
87 {
88  (void)name;
89 
90  switch (event) {
91  case T_EVENT_RUN_INITIALIZE_EARLY:
92  T_report_hash_sha256_initialize();
93  break;
94  case T_EVENT_RUN_FINALIZE_LATE:
95  T_report_hash_sha256_finalize();
96  break;
97  default:
98  break;
99  };
100 }