aboutsummaryrefslogtreecommitdiffstats
path: root/tests/test-sha1.c
blob: 3269d4d6097e9a933a3ee0c8bb426392ed9ec354 (plain)
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
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
/*
 * Test program for SHA1 and MD5
 * Copyright (c) 2003-2006, Jouni Malinen <j@w1.fi>
 *
 * This software may be distributed under the terms of the BSD license.
 * See README for more details.
 */

#include "includes.h"

#include "common.h"
#include "crypto/crypto.h"


static int cavp_shavs(const char *fname)
{
	FILE *f;
	int ret = 0;
	char buf[15000], *pos, *pos2;
	u8 msg[6400];
	int msg_len = 0, tmp_len;
	u8 md[20], hash[20];
	int ok = 0;

	printf("CAVP SHAVS test vectors from %s\n", fname);

	f = fopen(fname, "r");
	if (f == NULL) {
		printf("%s does not exist - cannot validate CAVP SHAVS test vectors\n",
			fname);
		return 0;
	}

	while (fgets(buf, sizeof(buf), f)) {
		pos = os_strchr(buf, '=');
		if (pos == NULL)
			continue;
		pos2 = pos - 1;
		while (pos2 >= buf && *pos2 == ' ')
			*pos2-- = '\0';
		*pos++ = '\0';
		while (*pos == ' ')
			*pos++ = '\0';
		pos2 = os_strchr(pos, '\r');
		if (!pos2)
			pos2 = os_strchr(pos, '\n');
		if (pos2)
			*pos2 = '\0';
		else
			pos2 = pos + os_strlen(pos);

		if (os_strcmp(buf, "Len") == 0) {
			msg_len = atoi(pos);
		} else if (os_strcmp(buf, "Msg") == 0) {
			tmp_len = os_strlen(pos);
			if (msg_len == 0 && tmp_len == 2)
				tmp_len = 0;
			if (msg_len != tmp_len * 4) {
				printf("Unexpected Msg length (msg_len=%u tmp_len=%u, Msg='%s'\n",
				       msg_len, tmp_len, pos);
				ret++;
				break;
			}

			if (hexstr2bin(pos, msg, msg_len / 8) < 0) {
				printf("Invalid hex string '%s'\n", pos);
				ret++;
				break;
			}
		} else if (os_strcmp(buf, "MD") == 0) {
			const u8 *addr[1];
			size_t len[1];

			tmp_len = os_strlen(pos);
			if (tmp_len != 2 * 20) {
				printf("Unexpected MD length (MD='%s'\n",
				       pos);
				ret++;
				break;
			}

			if (hexstr2bin(pos, md, 20) < 0) {
				printf("Invalid hex string '%s'\n", pos);
				ret++;
				break;
			}

			addr[0] = msg;
			len[0] = msg_len / 8;
			if (sha1_vector(1, addr, len, hash) < 0 ||
			    os_memcmp(hash, md, 20) != 0)
				ret++;
			else
				ok++;
		}
	}

	fclose(f);

	if (ret)
		printf("Test case failed\n");
	else
		printf("%d test vectors OK\n", ok);

	return ret;
}


int main(int argc, char *argv[])
{
	int ret = 0;

	if (cavp_shavs("CAVP/SHA1ShortMsg.rsp"))
		ret++;
	if (cavp_shavs("CAVP/SHA1LongMsg.rsp"))
		ret++;

	return ret;
}