safe_prime.cpp 1.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445
  1. ///////////////////////////////////////////////////////////////
  2. // Copyright 2012 John Maddock. Distributed under the Boost
  3. // Software License, Version 1.0. (See accompanying file
  4. // LICENSE_1_0.txt or copy at https://www.boost.org/LICENSE_1_0.txt
  5. //[safe_prime
  6. #include <boost/multiprecision/cpp_int.hpp>
  7. #include <boost/multiprecision/miller_rabin.hpp>
  8. #include <iostream>
  9. #include <iomanip>
  10. int main()
  11. {
  12. using namespace boost::random;
  13. using namespace boost::multiprecision;
  14. typedef cpp_int int_type;
  15. mt11213b base_gen(clock());
  16. independent_bits_engine<mt11213b, 256, int_type> gen(base_gen);
  17. //
  18. // We must use a different generator for the tests and number generation, otherwise
  19. // we get false positives.
  20. //
  21. mt19937 gen2(clock());
  22. for(unsigned i = 0; i < 100000; ++i)
  23. {
  24. int_type n = gen();
  25. if(miller_rabin_test(n, 25, gen2))
  26. {
  27. // Value n is probably prime, see if (n-1)/2 is also prime:
  28. std::cout << "We have a probable prime with value: " << std::hex << std::showbase << n << std::endl;
  29. if(miller_rabin_test((n-1)/2, 25, gen2))
  30. {
  31. std::cout << "We have a safe prime with value: " << std::hex << std::showbase << n << std::endl;
  32. return 0;
  33. }
  34. }
  35. }
  36. std::cout << "Ooops, no safe primes were found - probably a bad choice of seed values!" << std::endl;
  37. return 0;
  38. }
  39. //]