1 //
2 // Copyright 2019 Staysail Systems, Inc. <info@staysail.tech>
3 // Copyright 2018 Capitar IT Group BV <info@capitar.com>
4 //
5 // This software is supplied under the terms of the MIT License, a
6 // copy of which should be located in the distribution where this
7 // file was obtained (LICENSE.txt).  A copy of the license may also be
8 // found online at https://opensource.org/licenses/MIT.
9 //
10 
11 #include <stdint.h>
12 #include <string.h>
13 
14 #include <nng/nng.h>
15 
16 #include <acutest.h>
17 
18 #include "sha1.h"
19 
20 
21 // The following test vectors are from RFC 3174.
22 #define TEST1 "abc"
23 #define TEST2a "abcdbcdecdefdefgefghfghighijhi"
24 #define TEST2b "jkijkljklmklmnlmnomnopnopq"
25 #define TEST2 TEST2a TEST2b
26 #define TEST3 "a"
27 #define TEST4a "01234567012345670123456701234567"
28 #define TEST4b "01234567012345670123456701234567"
29 /* an exact multiple of 512 bits */
30 #define TEST4 TEST4a TEST4b
31 
32 char *testarray[4]   = { TEST1, TEST2, TEST3, TEST4 };
33 int   repeatcount[4] = { 1, 1, 1000000, 10 };
34 char *resultarray[4] = {
35 	"A9 99 3E 36 47 06 81 6A BA 3E 25 71 78 50 C2 6C 9C D0 D8 9D",
36 	"84 98 3E 44 1C 3B D2 6E BA AE 4A A1 F9 51 29 E5 E5 46 70 F1",
37 	"34 AA 97 3C D4 C4 DA A4 F6 1E EB 2B DB AD 27 31 65 34 01 6F",
38 	"DE A3 56 A2 CD DD 90 C7 A7 EC ED C5 EB B5 63 93 4F 46 04 52"
39 };
40 
41 void
test_sha1(void)42 test_sha1(void)
43 {
44 
45 	for (int i = 0; i < 4; i++) {
46 		nni_sha1_ctx ctx;
47 		size_t       slen = strlen(testarray[i]);
48 		uint8_t      digest[20];
49 		char         strout[20 * 3 + 1];
50 		char         name[8];
51 
52 		snprintf(name, sizeof(name), "%d", i);
53 		TEST_CASE(name);
54 
55 		memset(digest, 0, sizeof(digest));
56 		nni_sha1_init(&ctx);
57 		for (int j = 0; j < repeatcount[i]; j++) {
58 			nni_sha1_update(&ctx, (uint8_t *) testarray[i], slen);
59 		}
60 		nni_sha1_final(&ctx, digest);
61 		for (int j = 0; j < 20; j++) {
62 			snprintf(strout + j * 3, 4, "%02X ", digest[j]);
63 		}
64 		strout[20 * 3 - 1] = '\0';
65 		TEST_CHECK(strcmp(strout, resultarray[i]) == 0);
66 	}
67 }
68 
69 TEST_LIST = {
70 	{ "sha1", test_sha1 },
71 	{ NULL, NULL },
72 };
73