Coding a cryptography algorithm that accepts random bits from an unspecified source

Viewed 60

I'm currently coding a cryptography algorithm that I want to share on GitHub. This algorithm accepts random bits as input. I know that there are many possible sources of pseudorandom bits, one of the weirdest being that you can buy them. Because the quality and sources of pseudorandom number generators can vary widely, I want the user to be able to generate their own pseudorandom bits as input to my algorithm. I'm not sure how to code my algorithm in a general way since I don't know what data structure pseudorandom numbers come from in professional crytographic or statistical projects and how I should write a template function to access those pseudorandom numbers in the most general way.

The pseudorandom number generator will be accessed by my function my_distribution. I assume the PRNG will return a double between 0 and 1 or return a data type that I can convert to a double between 0 and 1.

double my_distribution([pseudorandom number generator]) {
    double random_number_from_my_distribution;
    // compute random_number_from_my_distribution using the PRNG
    return random_number_from_my_distribution;
}

There are a few possible sources for the pseudorandom bits I can think of.

  1. The pseudorandom bits could be stored in a file that is opened at run-time
  2. The pseudorandom bits could be provided by a (non-io) stream.
  3. The pseudorandom bits could be the return value of a function.
  4. The pseudorandom bits could be stored in some other data structure.

How should I accept pseudorandom bits into my_distribution? Why?

1 Answers

You can pass a function as a parameter in C++. Take a random generator function as a parameter for your algorithms. Not only this allows to plug in any generator, it also makes unit tests trivial:

#include <functional>

// The first generator
int generate_random() {
  return rand();
}

// The second generator good for tests
int generate_predictable_random() {
  return 17;
}

// Cryptography algorithm that uses the passed random generator.
void work_with_random(std::function<int()> random_generator) {
  int random_data = random_generator();
  printf("My random: %d\n", random_data);
}

int main() {
  work_with_random(generate_random);
  work_with_random(generate_predictable_random);
}
Related