This repository has been archived by the owner on Feb 4, 2021. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathtest_hex.c
99 lines (77 loc) · 1.88 KB
/
test_hex.c
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
// test_hex.c
// 2020-03-07 Markku-Juhani O. Saarinen <[email protected]>
// Copyright (c) 2020, PQShield Ltd. All rights reserved.
// functions to facilitate simple runtime tests
#include "test_hex.h"
// single hex digit
static int hexdigit(char ch)
{
if (ch >= '0' && ch <= '9')
return ch - '0';
if (ch >= 'A' && ch <= 'F')
return ch - 'A' + 10;
if (ch >= 'a' && ch <= 'f')
return ch - 'a' + 10;
return -1;
}
// read a hex string of "maxbytes", return byte length
size_t readhex(uint8_t * buf, size_t maxbytes, const char *str)
{
size_t i;
int h, l;
for (i = 0; i < maxbytes; i++) {
h = hexdigit(str[2 * i]);
if (h < 0)
return i;
l = hexdigit(str[2 * i + 1]);
if (l < 0)
return i;
buf[i] = (h << 4) + l;
}
return i;
}
// print hexadecimal "data", length "len", with label "lab"
void prthex(const char *lab, const void *data, size_t len)
{
size_t i;
uint8_t x;
printf("[TEST] %s ", lab);
const char hex[] = "0123456789ABCDEF";
for (i = 0; i < len; i++) {
x = ((const uint8_t *) data)[i];
putchar(hex[(x >> 4) & 0xF]);
putchar(hex[x & 0xF]);
}
putchar('\n');
}
// check "data" of "len" bytes against a hexadecimal test vector "ref"
int chkhex(const char *lab, const void *data, size_t len, const char *ref)
{
size_t i;
uint8_t x;
int fail = 0;
// check equivalence
for (i = 0; i < len; i++) {
x = ((const uint8_t *) data)[i];
if (hexdigit(ref[2 * i]) != ((x >> 4) & 0xF) ||
hexdigit(ref[2 * i + 1]) != (x & 0x0F)) {
fail = 1;
break;
}
}
if (i == len && hexdigit(ref[2 * len]) >= 0) {
fail = 1;
}
printf("[%s] %s %s\n", fail ? "FAIL" : "PASS", lab, ref);
if (fail) {
prthex(lab, data, len);
}
return fail;
}
// boolean return value check
int chkret(const char *lab, int want, int have)
{
printf("[%s] %s WANT=%d HAVE=%d\n",
want != have ? "FAIL" : "PASS", lab, want, have);
return want != have ? 1 : 0;
}