Initial revision
[silc.git] / lib / silccrypt / tests / test_rsa.c
1 #include <stdio.h>
2 #include <stdlib.h>
3
4 #include "silcincludes.h"
5 #include "rsa.h"
6 #include "rsa_internal.h"
7
8 void testi(SilcRng rng, void *context)
9 {
10         char *numbuf;
11         unsigned int bytes;
12         unsigned int i;
13         MP_INT tnum;            /* number we'll encrypt */
14         MP_INT test;            /* en/decrypted result of tnum */
15         RsaKey *key = (RsaKey *)context;
16         int bits = 1024;        
17
18         numbuf = (char *)malloc((bits / 3) + 1);
19         bytes = bits / 10;
20             
21         mpz_init(&tnum);
22         mpz_init(&test);
23         
24         fprintf(stderr, "\nTesting encryption and decryption ... ");
25
26         for(i = 0; i < bytes; i++)
27             sprintf(numbuf + 2 * i, "%02x", silc_rng_get_byte(rng));
28         
29         mpz_set_str(&tnum, numbuf, 16);
30
31         /* empty buffer */
32         memset(numbuf, 0, bits / 3);
33         free(numbuf);
34
35         /* make tnum smaller than n */
36         mpz_div_ui(&tnum, &tnum, 10);
37         /* encrypt */
38         rsa_en_de_crypt(&test, &tnum, &key->e, &key->n);
39         /* decrypt */
40         rsa_en_de_crypt(&test, &test, &key->d, &key->n);
41         /* see if decrypted result is same than the original one is */
42         if (mpz_cmp(&test, &tnum) != 0) {
43             fprintf(stderr, "Error in encryption and decryption!\n");
44             return -1;
45         }
46
47         mpz_clear(&tnum);
48         mpz_clear(&test);
49
50         fprintf(stderr, "Keys are Ok.\n");
51 }
52
53 int main()
54 {
55         SilcPKCS pkcs;
56         SilcRng rng;
57         unsigned char *pk, *prv;
58         unsigned int pk_len, prv_len;
59         unsigned char *src, *dst, *new;
60         unsigned int src_len, dst_len, new_len;
61         SilcInt tnum, test;
62
63         silc_pkcs_alloc("rsa", &pkcs);
64
65         rng = silc_rng_alloc();
66         silc_rng_init(rng);
67         silc_math_primegen_init();
68
69         pkcs->pkcs->init(pkcs->context, 1024, rng);
70         
71         pk = silc_pkcs_get_public_key(pkcs, &pk_len);
72         prv = silc_pkcs_get_public_key(pkcs, &prv_len);
73
74         src = "PEKKA RIIKONEN";
75         src_len = 5;
76         dst = silc_calloc(200, sizeof(unsigned char));
77         pkcs->pkcs->encrypt(pkcs->context, src, src_len, dst, &dst_len);
78
79         SILC_LOG_HEXDUMP(("src"), src, src_len);
80         SILC_LOG_HEXDUMP(("dst"), dst, dst_len);
81
82         new = silc_calloc(200, sizeof(unsigned char));
83         pkcs->pkcs->decrypt(pkcs->context, dst, dst_len, new, &new_len);
84
85         SILC_LOG_HEXDUMP(("new"), new, new_len);
86
87         testi(rng, pkcs->context);
88
89         return 0;
90 }