1 #include <test.h>
2
3 #include <unistd.h>
4 #include <string.h>
5 #include <key.h>
6 #include <openssl/rsa.h>
7 #include <openssl/evp.h>
8 #include <openssl/bn.h>
9
10 /*
11 * Initialization
12 */
13 static int initialized = 0;
14 static RSA *rsa = NULL;
test_setup()15 void test_setup()
16 {
17 rsa = RSA_new();
18 if (rsa)
19 {
20 BIGNUM *bn = NULL;
21 bn = BN_new();
22 if (!bn)
23 {
24 RSA_free(rsa);
25 initialized = 0;
26 return;
27 }
28 BN_set_word(bn, RSA_F4);
29 RSA_generate_key_ex(rsa, 1024, bn, NULL);
30 BN_free(bn);
31 }
32 initialized = 1;
33 }
34
test_teardown()35 void test_teardown()
36 {
37 rsa = NULL;
38 initialized = 0;
39 }
40 #define ASSERT_IF_NOT_INITIALIZED \
41 assert_int_equal(1, initialized)
42 /*
43 * Tests
44 */
test_key_basic(void)45 static void test_key_basic(void)
46 {
47 test_setup();
48 ASSERT_IF_NOT_INITIALIZED;
49 Key *key = NULL;
50 assert_true(key == NULL);
51 key = KeyNew(rsa, HASH_METHOD_MD5);
52 assert_true(key != NULL);
53 assert_int_equal(HASH_METHOD_MD5, KeyHashMethod(key));
54 assert_true(rsa == KeyRSA(key));
55 unsigned int length = 0;
56 assert_true(KeyBinaryHash(key, &length) != NULL);
57 assert_int_equal(CF_MD5_LEN, length);
58 assert_true(KeyPrintableHash(key) != NULL);
59 /* Negative cases */
60 assert_true(KeyNew(NULL, HASH_METHOD_MD5) == NULL);
61 assert_true(KeyNew(rsa, HASH_METHOD_NONE) == NULL);
62 assert_true(KeyNew(NULL, HASH_METHOD_NONE) == NULL);
63 /* Finish */
64 KeyDestroy(&key);
65 assert_true(key == NULL);
66 test_teardown();
67 }
68
test_key_hash(void)69 static void test_key_hash(void)
70 {
71 test_setup();
72 ASSERT_IF_NOT_INITIALIZED;
73 Key *key = NULL;
74 assert_true(key == NULL);
75 key = KeyNew(rsa, HASH_METHOD_MD5);
76 assert_true(key != NULL);
77 assert_int_equal(HASH_METHOD_MD5, KeyHashMethod(key));
78 /* We now examine the first four bytes of the hash, to check the printable bit */
79 const char *md5_hash = KeyPrintableHash(key);
80 assert_true((md5_hash[0] == 'M') && (md5_hash[1] == 'D') && (md5_hash[2] == '5') && (md5_hash[3] == '='));
81 /* When we change the hashing algorithm, a new hash is automatically generated. */
82 assert_int_equal(0, KeySetHashMethod(key, HASH_METHOD_SHA256));
83 const char *sha256_hash = KeyPrintableHash(key);
84 assert_true((sha256_hash[0] == 'S') && (sha256_hash[1] == 'H') && (sha256_hash[2] == 'A') && (sha256_hash[3] == '='));
85 KeyDestroy(&key);
86 test_teardown();
87 }
88
89 /*
90 * Main routine
91 * Notice the calls to both setup and teardown.
92 */
main()93 int main()
94 {
95 PRINT_TEST_BANNER();
96 const UnitTest tests[] =
97 {
98 unit_test(test_key_basic),
99 unit_test(test_key_hash)
100 };
101 OpenSSL_add_all_digests();
102 int result = run_tests(tests);
103 return result;
104 }
105