divtest.c 1007 B

123456789101112131415161718192021222324252627282930313233343536373839404142
  1. #include <openssl/bn.h>
  2. #include <openssl/rand.h>
  3. static int Rand(n)
  4. {
  5. unsigned char x[2];
  6. RAND_pseudo_bytes(x, 2);
  7. return (x[0] + 2 * x[1]);
  8. }
  9. static void bug(char *m, BIGNUM *a, BIGNUM *b)
  10. {
  11. printf("%s!\na=", m);
  12. BN_print_fp(stdout, a);
  13. printf("\nb=");
  14. BN_print_fp(stdout, b);
  15. printf("\n");
  16. fflush(stdout);
  17. }
  18. main()
  19. {
  20. BIGNUM *a = BN_new(), *b = BN_new(), *c = BN_new(), *d = BN_new(),
  21. *C = BN_new(), *D = BN_new();
  22. BN_RECP_CTX *recp = BN_RECP_CTX_new();
  23. BN_CTX *ctx = BN_CTX_new();
  24. for (;;) {
  25. BN_pseudo_rand(a, Rand(), 0, 0);
  26. BN_pseudo_rand(b, Rand(), 0, 0);
  27. if (BN_is_zero(b))
  28. continue;
  29. BN_RECP_CTX_set(recp, b, ctx);
  30. if (BN_div(C, D, a, b, ctx) != 1)
  31. bug("BN_div failed", a, b);
  32. if (BN_div_recp(c, d, a, recp, ctx) != 1)
  33. bug("BN_div_recp failed", a, b);
  34. else if (BN_cmp(c, C) != 0 || BN_cmp(c, C) != 0)
  35. bug("mismatch", a, b);
  36. }
  37. }