thegreatunclean

Example RNG api

Jan 9th, 2021
895
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. #include <stdlib.h>
  2. #include <time.h>
  3. #include <stdio.h>
  4.  
  5. //Give the function pointer a pretty name
  6. //Defines the API that users must fit
  7. typedef void(*RNGFunc)(char*,int);
  8.  
  9. void gen_rsa_key(RNGFunc rng) {
  10.     //I want 10 random bytes!
  11.     char buff[10];
  12.     rng(buff, 10);
  13.     //use those random bytes...
  14.     //etc
  15. }
  16.  
  17. //Fill arr with len random bytes
  18. void my_bad_rng(char *arr, int len) {
  19.     srand(time(NULL));
  20.     for(int i=0; i < len; i++) {
  21.         arr[i] = (char)(rand() % 255);
  22.     }
  23. }
  24.  
  25. void better_unix_rng(char *arr, int len) {
  26.     FILE* urandom = fopen("/dev/urandom", "r");
  27.     if (urandom != NULL) {
  28.         fread(arr, 1, 10, urandom);
  29.     } else {
  30.         //couldn't open /dev/urandom
  31.         //PANIC!!
  32.         abort();
  33.     }
  34. }
  35.  
  36. int main() {
  37.     gen_rsa_key(my_bad_rng);
  38.     gen_rsa_key(better_unix_rng);
  39. }
RAW Paste Data