Skip to content

Instantly share code, notes, and snippets.

@colmmacc
Last active January 13, 2016 18:38
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save colmmacc/c8d6f848d3261271dc91 to your computer and use it in GitHub Desktop.
Save colmmacc/c8d6f848d3261271dc91 to your computer and use it in GitHub Desktop.
An RNG API for OpenSSL
#include <openssl/rand.h>
void example() {
/* Initialize the random subsystem. generally called prior to chroot, may fail if /dev/urandom is not available. */
RNG_init();
/* alternatively, a more future-flexible OpenSSL init that calls RNG_init() internally. Similar to SSL_library_init, but more general. */
OPENSSL_init();
/* Instantiate an RNG */
RNG_CTX *rng = RNG_CTX_Init();
/* Instantiate an RNG with a personalization string. The NIST specs use these, and they are a
* little voodoo-ish in their theory, but do provide some value in corner cases */
RNG_CTX *rng = RNG_CTX_Init(uint8_t *ps, ssize_t size);
/* Produce randomly generated data */
int r = RNG_generate(rng, uint8_t *data, ssize_t size);
/* Pick a random int such that 0 < n < max. Return -1 on error.
* I suggest including this because it means the RNG honors its name and generates
* random numbers. Callers often screw this up by either doing naive mod, or by
* multiplying a radom float. Might as well give them something to do it the right
* way.
*/
int n = RNG_rand(rng, max);
/* Destructor for the rng */
RNG_CTX_free(rng);
/* One could imagine other routines taking rng as an argument; for example a function
* to produce normal, or log-normally distributed numbers. The TLS/SSL code could also
* pass along RNG instances as part of its context.
*/
/* Deliberately absent: any way to seed, reseed, over-ride, or save. Callers often screw these up. */
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment