aboutsummaryrefslogtreecommitdiffstats
path: root/src/cmd/rng.cpp
blob: b89376b4c9a870470560c5ecd3802931e19411c5 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
/*
* (C) 2014 Jack Lloyd
*
* Botan is released under the Simplified BSD License (see license.txt)
*/

#include "apps.h"
#include <botan/entropy_src.h>
#include <botan/auto_rng.h>

#if defined(BOTAN_HAS_SYSTEM_RNG)
  #include <botan/system_rng.h>
#endif

namespace {

int rng(int argc, char* argv[])
   {
   if(argc == 1)
      {
      std::cout << "Usage: " << argv[0] << " [--raw-entropy] [n]" << std::endl;
      return 1;
      }

   try
      {
      const size_t amt = to_u32bit(argv[argc-1]);
      const bool raw = (argc == 3 && std::string(argv[1]) == "--raw-entropy");

#if defined(BOTAN_HAS_SYSTEM_RNG)
      std::cout << "System " << hex_encode(system_rng().random_vec(amt)) << std::endl;
#endif

      if(!raw)
         {
         AutoSeeded_RNG rng;
         std::cout << hex_encode(rng.random_vec(amt)) << std::endl;
         }
      else
         {
         double total_collected = 0;

         Entropy_Accumulator accum(
            [amt,&total_collected](const byte in[], size_t in_len, double entropy_estimate)
            {
            std::cout << "Collected estimated "<< entropy_estimate << " bits in "
                      << hex_encode(in, in_len) << std::endl;
            total_collected += entropy_estimate;
            return total_collected >= amt;
            });

         Entropy_Sources::global_sources().poll(accum);
         }
      }
   catch(std::exception& e)
      {
      std::cout << "Error: " << e.what() << std::endl;
      return 1;
      }

   return 0;
   }

REGISTER_APP(rng);

}