1 // SPDX-License-Identifier: GPL-2.0
2 #include "tests.h"
3 #include "util/debug.h"
4 #include "util/sha1.h"
5
6 #include <linux/compiler.h>
7 #include <stdlib.h>
8 #include <string2.h>
9
test_strreplace(char needle,const char * haystack,const char * replace,const char * expected)10 static int test_strreplace(char needle, const char *haystack,
11 const char *replace, const char *expected)
12 {
13 char *new = strreplace_chars(needle, haystack, replace);
14 int ret = strcmp(new, expected);
15
16 free(new);
17 return ret == 0;
18 }
19
20 #define MAX_LEN 512
21
22 /* Test sha1() for all lengths from 0 to MAX_LEN inclusively. */
test_sha1(void)23 static int test_sha1(void)
24 {
25 u8 data[MAX_LEN];
26 size_t digests_size = (MAX_LEN + 1) * SHA1_DIGEST_SIZE;
27 u8 *digests;
28 u8 digest_of_digests[SHA1_DIGEST_SIZE];
29 /*
30 * The correctness of this value was verified by running this test with
31 * sha1() replaced by OpenSSL's SHA1().
32 */
33 static const u8 expected_digest_of_digests[SHA1_DIGEST_SIZE] = {
34 0x74, 0xcd, 0x4c, 0xb9, 0xd8, 0xa6, 0xd5, 0x95, 0x22, 0x8b,
35 0x7e, 0xd6, 0x8b, 0x7e, 0x46, 0x95, 0x31, 0x9b, 0xa2, 0x43,
36 };
37 size_t i;
38
39 digests = malloc(digests_size);
40 TEST_ASSERT_VAL("failed to allocate digests", digests != NULL);
41
42 /* Generate MAX_LEN bytes of data. */
43 for (i = 0; i < MAX_LEN; i++)
44 data[i] = i;
45
46 /* Calculate a SHA-1 for each length 0 through MAX_LEN inclusively. */
47 for (i = 0; i <= MAX_LEN; i++)
48 sha1(data, i, &digests[i * SHA1_DIGEST_SIZE]);
49
50 /* Calculate digest of all digests calculated above. */
51 sha1(digests, digests_size, digest_of_digests);
52
53 free(digests);
54
55 /* Check for the expected result. */
56 TEST_ASSERT_VAL("wrong output from sha1()",
57 memcmp(digest_of_digests, expected_digest_of_digests,
58 SHA1_DIGEST_SIZE) == 0);
59 return 0;
60 }
61
test__util(struct test_suite * t __maybe_unused,int subtest __maybe_unused)62 static int test__util(struct test_suite *t __maybe_unused, int subtest __maybe_unused)
63 {
64 TEST_ASSERT_VAL("empty string", test_strreplace(' ', "", "123", ""));
65 TEST_ASSERT_VAL("no match", test_strreplace('5', "123", "4", "123"));
66 TEST_ASSERT_VAL("replace 1", test_strreplace('3', "123", "4", "124"));
67 TEST_ASSERT_VAL("replace 2", test_strreplace('a', "abcabc", "ef", "efbcefbc"));
68 TEST_ASSERT_VAL("replace long", test_strreplace('a', "abcabc", "longlong",
69 "longlongbclonglongbc"));
70
71 return test_sha1();
72 }
73
74 DEFINE_SUITE("util", util);
75