1.1 --- /dev/null Thu Jan 01 00:00:00 1970 +0000 1.2 +++ b/security/nss/lib/freebl/mpi/utils/metime.c Wed Dec 31 06:09:35 2014 +0100 1.3 @@ -0,0 +1,100 @@ 1.4 +/* 1.5 + * metime.c 1.6 + * 1.7 + * Modular exponentiation timing test 1.8 + * 1.9 + * This Source Code Form is subject to the terms of the Mozilla Public 1.10 + * License, v. 2.0. If a copy of the MPL was not distributed with this 1.11 + * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ 1.12 + 1.13 +#include <stdio.h> 1.14 +#include <stdlib.h> 1.15 +#include <string.h> 1.16 +#include <limits.h> 1.17 +#include <time.h> 1.18 + 1.19 +#include "mpi.h" 1.20 +#include "mpprime.h" 1.21 + 1.22 +double clk_to_sec(clock_t start, clock_t stop); 1.23 + 1.24 +int main(int argc, char *argv[]) 1.25 +{ 1.26 + int ix, num, prec = 8; 1.27 + unsigned int seed; 1.28 + clock_t start, stop; 1.29 + double sec; 1.30 + 1.31 + mp_int a, m, c; 1.32 + 1.33 + if(getenv("SEED") != NULL) 1.34 + seed = abs(atoi(getenv("SEED"))); 1.35 + else 1.36 + seed = (unsigned int)time(NULL); 1.37 + 1.38 + if(argc < 2) { 1.39 + fprintf(stderr, "Usage: %s <num-tests> [<nbits>]\n", argv[0]); 1.40 + return 1; 1.41 + } 1.42 + 1.43 + if((num = atoi(argv[1])) < 0) 1.44 + num = -num; 1.45 + 1.46 + if(!num) { 1.47 + fprintf(stderr, "%s: must perform at least 1 test\n", argv[0]); 1.48 + return 1; 1.49 + } 1.50 + 1.51 + if(argc > 2) { 1.52 + if((prec = atoi(argv[2])) <= 0) 1.53 + prec = 8; 1.54 + else 1.55 + prec = (prec + (DIGIT_BIT - 1)) / DIGIT_BIT; 1.56 + 1.57 + } 1.58 + 1.59 + printf("Modular exponentiation timing test\n" 1.60 + "Precision: %d digits (%d bits)\n" 1.61 + "# of tests: %d\n\n", prec, prec * DIGIT_BIT, num); 1.62 + 1.63 + mp_init_size(&a, prec); 1.64 + mp_init_size(&m, prec); 1.65 + mp_init_size(&c, prec); 1.66 + 1.67 + srand(seed); 1.68 + 1.69 + start = clock(); 1.70 + for(ix = 0; ix < num; ix++) { 1.71 + 1.72 + mpp_random_size(&a, prec); 1.73 + mpp_random_size(&c, prec); 1.74 + mpp_random_size(&m, prec); 1.75 + /* set msb and lsb of m */ 1.76 + DIGIT(&m,0) |= 1; 1.77 + DIGIT(&m, USED(&m)-1) |= (mp_digit)1 << (DIGIT_BIT - 1); 1.78 + if (mp_cmp(&a, &m) > 0) 1.79 + mp_sub(&a, &m, &a); 1.80 + 1.81 + mp_exptmod(&a, &c, &m, &c); 1.82 + } 1.83 + stop = clock(); 1.84 + 1.85 + sec = clk_to_sec(start, stop); 1.86 + 1.87 + printf("Total: %.3f seconds\n", sec); 1.88 + printf("Individual: %.3f seconds\n", sec / num); 1.89 + 1.90 + mp_clear(&c); 1.91 + mp_clear(&a); 1.92 + mp_clear(&m); 1.93 + 1.94 + return 0; 1.95 +} 1.96 + 1.97 +double clk_to_sec(clock_t start, clock_t stop) 1.98 +{ 1.99 + return (double)(stop - start) / CLOCKS_PER_SEC; 1.100 +} 1.101 + 1.102 +/*------------------------------------------------------------------------*/ 1.103 +/* HERE THERE BE DRAGONS */