depmaker
[tridge/junkcode.git] / timing_attack.c
1 #include <stdio.h>
2 #include <sys/time.h>
3 #include <time.h>
4 #include <string.h>
5
6
7 static struct timeval tp1,tp2;
8
9 static void start_timer()
10 {
11         gettimeofday(&tp1,NULL);
12 }
13
14 static double end_timer()
15 {
16         gettimeofday(&tp2,NULL);
17         return (tp2.tv_sec + (tp2.tv_usec*1.0e-6)) - 
18                 (tp1.tv_sec + (tp1.tv_usec*1.0e-6));
19 }
20
21 static void attack_it(const char *target, int len)
22 {
23         int i;
24         double totals[256];
25         double this_run[256];
26         char teststr[len+1];
27         int c, r, runs, min_c;
28         double min;
29
30         runs = 1000000;
31
32
33         for (i=0;i<len;i++) {
34                 memset(totals, 0, sizeof(totals));
35
36                 for (r=0;r<runs;r++) {
37                         for (c=0;c<256;c++) {
38                                 start_timer();
39                                 teststr[i] = c;
40                                 memcmp(teststr, target, i+1);
41                                 this_run[c] = end_timer();
42                         }
43                         for (c=0;c<256;c++) {
44 //                              printf("%3d %lf\n", c, 1000*1000*this_run[c]);
45                                 totals[c] += this_run[c];
46                         }
47                 }
48
49                 min_c = 0;
50                 min = totals[0];
51                 for (c=1;c<256;c++) {
52                         if (totals[c] < min) {
53                                 min = totals[c];
54                                 min_c = c;
55                         }
56                 }
57                 printf("min_c=%d\n", min_c);
58         }
59 }
60
61 int main(int argc, char *argv[])
62 {
63         attack_it(argv[1], strlen(argv[1]));
64         return 0;
65 }