bignum.c 2.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091
  1. /*
  2. * Copyright 2016 The OpenSSL Project Authors. All Rights Reserved.
  3. *
  4. * Licensed under the OpenSSL licenses, (the "License");
  5. * you may not use this file except in compliance with the License.
  6. * You may obtain a copy of the License at
  7. * https://www.openssl.org/source/license.html
  8. * or in the file LICENSE in the source distribution.
  9. */
  10. /*
  11. * Confirm that a^b mod c agrees when calculated cleverly vs naively, for
  12. * random a, b and c.
  13. */
  14. #include <stdio.h>
  15. #include <openssl/bn.h>
  16. #include "fuzzer.h"
  17. int LLVMFuzzerTestOneInput(const uint8_t *buf, size_t len) {
  18. int success = 0;
  19. static BN_CTX *ctx;
  20. static BN_MONT_CTX *mont;
  21. static BIGNUM *b1;
  22. static BIGNUM *b2;
  23. static BIGNUM *b3;
  24. static BIGNUM *b4;
  25. static BIGNUM *b5;
  26. if (ctx == NULL) {
  27. b1 = BN_new();
  28. b2 = BN_new();
  29. b3 = BN_new();
  30. b4 = BN_new();
  31. b5 = BN_new();
  32. ctx = BN_CTX_new();
  33. mont = BN_MONT_CTX_new();
  34. }
  35. // Divide the input into three parts, using the values of the first two
  36. // bytes to choose lengths, which generate b1, b2 and b3. Use three bits
  37. // of the third byte to choose signs for the three numbers.
  38. size_t l1 = 0, l2 = 0, l3 = 0;
  39. int s1 = 0, s2 = 0, s3 = 0;
  40. if (len > 2) {
  41. len -= 3;
  42. l1 = (buf[0] * len) / 255;
  43. ++buf;
  44. l2 = (buf[0] * (len - l1)) / 255;
  45. ++buf;
  46. l3 = len - l1 - l2;
  47. s1 = buf[0] & 1;
  48. s2 = buf[0] & 2;
  49. s3 = buf[0] & 4;
  50. ++buf;
  51. }
  52. OPENSSL_assert(BN_bin2bn(buf, l1, b1) == b1);
  53. BN_set_negative(b1, s1);
  54. OPENSSL_assert(BN_bin2bn(buf + l1, l2, b2) == b2);
  55. BN_set_negative(b2, s2);
  56. OPENSSL_assert(BN_bin2bn(buf + l1 + l2, l3, b3) == b3);
  57. BN_set_negative(b3, s3);
  58. // mod 0 is undefined
  59. if (BN_is_zero(b3)) {
  60. success = 1;
  61. goto done;
  62. }
  63. OPENSSL_assert(BN_mod_exp(b4, b1, b2, b3, ctx));
  64. OPENSSL_assert(BN_mod_exp_simple(b5, b1, b2, b3, ctx));
  65. success = BN_cmp(b4, b5) == 0;
  66. if (!success) {
  67. BN_print_fp(stdout, b1);
  68. putchar('\n');
  69. BN_print_fp(stdout, b2);
  70. putchar('\n');
  71. BN_print_fp(stdout, b3);
  72. putchar('\n');
  73. BN_print_fp(stdout, b4);
  74. putchar('\n');
  75. BN_print_fp(stdout, b5);
  76. putchar('\n');
  77. }
  78. done:
  79. OPENSSL_assert(success);
  80. return 0;
  81. }