group_bench.c 2.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990
  1. #include "config.h"
  2. #include <stdio.h>
  3. #include <gmp.h>
  4. #include <openssl/ossl_typ.h>
  5. #include <openssl/bio.h>
  6. #include <openssl/bn.h>
  7. #include <openssl/evp.h>
  8. #include <openssl/ec.h>
  9. #include "entropy.h"
  10. #include "group.h"
  11. #include "timeit.h"
  12. void EC_POINT_get_random(const EC_GROUP *group, EC_POINT *r, BN_CTX *ctx) {
  13. BIGNUM *k = NULL;
  14. k = BN_new();
  15. if (!EC_GROUP_get_order(group, k, ctx)) goto err;
  16. if (!BN_pseudo_rand(k, BN_num_bits(k), 0, 0)) goto err;
  17. if (!EC_POINT_mul(group, r, k, NULL, NULL, ctx)) goto err;
  18. if (!EC_POINT_is_on_curve(group, r, ctx)) goto err;
  19. err:
  20. if (k) BN_free(k);
  21. }
  22. int main()
  23. {
  24. mpz_entropy_init();
  25. group_init();
  26. mpz_t x, y, xy;
  27. mpz_inits(x, y, xy, NULL);
  28. BN_CTX *ctx;
  29. EC_GROUP *group;
  30. EC_POINT *P, *Q;
  31. ctx = BN_CTX_new();
  32. group = EC_GROUP_new_by_curve_name(NID_secp521r1);
  33. for (int n = 0; n < (int) 1e3; n++) {
  34. /* block for Z_p with our reminder */
  35. {
  36. INIT_TIMEIT(CLOCK_PROCESS_CPUTIME_ID);
  37. for (int i = 0; i < (int) 1e5; i++) {
  38. mpz_urandomm(x, _rstate, p);
  39. mpz_urandomm(y, _rstate, p);
  40. START_TIMEIT();
  41. mul_modp(xy, x, y);
  42. END_TIMEIT();
  43. }
  44. printf(TIMEIT_FORMAT SEP, GET_TIMEIT());
  45. }
  46. /* block for Z_p with vanilla reminder */
  47. {
  48. INIT_TIMEIT(CLOCK_PROCESS_CPUTIME_ID);
  49. for (int i = 0; i < (int) 1e5; i++) {
  50. mpz_urandomm(x, _rstate, p);
  51. mpz_urandomm(y, _rstate, p);
  52. START_TIMEIT();
  53. mpz_mul(xy, x, y);
  54. mpz_mod(xy, xy, p);
  55. END_TIMEIT();
  56. }
  57. printf(TIMEIT_FORMAT SEP, GET_TIMEIT());
  58. }
  59. /* EC addition */
  60. {
  61. INIT_TIMEIT(CLOCK_PROCESS_CPUTIME_ID);
  62. for (int i = 0; i < (int) 1e5; i++) {
  63. P = EC_POINT_new(group);
  64. Q = EC_POINT_new(group);
  65. EC_POINT_get_random(group, Q, ctx);
  66. START_TIMEIT();
  67. EC_POINT_add(group, Q, Q, P, ctx);
  68. END_TIMEIT();
  69. }
  70. printf(TIMEIT_FORMAT "\n", GET_TIMEIT());
  71. }
  72. }
  73. mpz_clears(x, y, xy, NULL);
  74. }