Merge pull request #678 from libtom/some-improvements
[libtomcrypt.git] / tests / pkcs_1_test.c
blobde0f7d307b25c7c9c99bc2f87d52dde196c4d1fe
1 /* LibTomCrypt, modular cryptographic library -- Tom St Denis */
2 /* SPDX-License-Identifier: Unlicense */
3 #include <tomcrypt_test.h>
5 #ifdef LTC_PKCS_1
7 #ifdef LTC_TEST_REAL_RAND
8 #define LTC_TEST_RAND_SEED time(NULL)
9 #else
10 #define LTC_TEST_RAND_SEED 23
11 #endif
13 int pkcs_1_test(void)
15 unsigned char buf[3][128];
16 int res1, res2, res3, prng_idx, hash_idx;
17 unsigned long x, y, l1, l2, l3, i1, lparamlen, saltlen, modlen;
18 static const unsigned char lparam[] = { 1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16 };
20 /* get hash/prng */
21 hash_idx = find_hash("sha1");
22 prng_idx = find_prng("yarrow");
24 if (hash_idx == -1 || prng_idx == -1) {
25 fprintf(stderr, "pkcs_1 tests require sha1/yarrow");
26 return 1;
29 srand(LTC_TEST_RAND_SEED);
30 /* do many tests */
31 for (x = 0; x < 100; x++) {
32 zeromem(buf, sizeof(buf));
34 /* make a dummy message (of random length) */
35 l3 = (rand() & 31) + 8;
36 for (y = 0; y < l3; y++) buf[0][y] = rand() & 255;
38 /* pick a random lparam len [0..16] */
39 lparamlen = abs(rand()) % 17;
41 /* pick a random saltlen 0..16 */
42 saltlen = abs(rand()) % 17;
44 /* PKCS #1 v2.0 supports modlens not multiple of 8 */
45 modlen = 800 + (abs(rand()) % 224);
47 /* encode it */
48 l1 = sizeof(buf[1]);
49 DO(pkcs_1_oaep_encode(buf[0], l3, lparam, lparamlen, modlen, &yarrow_prng, prng_idx, hash_idx, -1, buf[1], &l1));
51 /* decode it */
52 l2 = sizeof(buf[2]);
53 DO(pkcs_1_oaep_decode(buf[1], l1, lparam, lparamlen, modlen, hash_idx, -1, buf[2], &l2, &res1));
55 if (res1 != 1 || l2 != l3 || memcmp(buf[2], buf[0], l3) != 0) {
56 fprintf(stderr, "Outsize == %lu, should have been %lu, res1 = %d, lparamlen = %lu, msg contents follow.\n", l2, l3, res1, lparamlen);
57 fprintf(stderr, "ORIGINAL:\n");
58 for (x = 0; x < l3; x++) {
59 fprintf(stderr, "%02x ", buf[0][x]);
61 fprintf(stderr, "\nRESULT:\n");
62 for (x = 0; x < l2; x++) {
63 fprintf(stderr, "%02x ", buf[2][x]);
65 fprintf(stderr, "\n\n");
66 return 1;
69 /* test PSS */
70 l1 = sizeof(buf[1]);
71 DO(pkcs_1_pss_encode(buf[0], l3, saltlen, &yarrow_prng, prng_idx, hash_idx, modlen, buf[1], &l1));
72 DO(pkcs_1_pss_decode(buf[0], l3, buf[1], l1, saltlen, hash_idx, modlen, &res1));
74 buf[0][i1 = abs(rand()) % l3] ^= 1;
75 DO(pkcs_1_pss_decode(buf[0], l3, buf[1], l1, saltlen, hash_idx, modlen, &res2));
77 buf[0][i1] ^= 1;
78 buf[1][abs(rand()) % (l1 - 1)] ^= 1;
79 pkcs_1_pss_decode(buf[0], l3, buf[1], l1, saltlen, hash_idx, modlen, &res3);
80 if (!(res1 == 1 && res2 == 0 && res3 == 0)) {
81 fprintf(stderr, "PSS failed: %d, %d, %d, %lu, %lu\n", res1, res2, res3, l3, saltlen);
82 return 1;
85 return 0;
88 #else
90 int pkcs_1_test(void)
92 return CRYPT_NOP;
95 #endif