This repository has been archived on 2022-02-10. You can view files and clone it, but cannot push or open issues or pull requests.
fortuna/generator.cpp
2021-10-27 18:56:14 +02:00

66 lines
1.5 KiB
C++

#include <cmath>
#include <cassert>
#include <stdexcept>
#include <tuple>
#include "generator.h"
using namespace std;
struct G_state{
long k;
unsigned __int128 ctr;
};
G_state *initialize_generator(){
auto G = new G_state;
G->k = 0;
G->ctr = 0;
return G;
};
string do_crypto(long k, unsigned __int128 ctr){
/* this function calls the block cipher
* returns a string of k*(16 bytes);
do whatever atm */
k = 0;
ctr = 0;
return "";
}
/* lacking objects, we have to return both the state and the string */
tuple<string, G_state> generate_blocks(G_state G, int k_blocks){
assert (G.ctr!=0);
string r = "";
for (int i = 0; i < k_blocks; ++i) {
r += do_crypto(G.k, G.ctr);
G.ctr += 1;
}
return {r, G};
}
/* n is number of random bytes to generate */
tuple<string, G_state> generate_random_data(G_state G, uint n){
string r = "";
if (n < 0){
/* this should not be possible */
printf("[*] error: n cannot be < 0\n");
throw invalid_argument("n cannot be < 0");
} else if (n > pow(2,20)){
printf("[*] error: n cannot be > 2^20\n");
throw invalid_argument("n cannot be > 2^20");
}
/* do magic to compute r
* r ← first-n-bytes(GenerateBlocks(G, ceil(n/16) )) */
string rr = std::get<0>(generate_blocks(G,ceil(n/16)));
r = rr.substr(0,n);
/* re-key */
// TODO: check conversions
G.k = stoul(std::get<0>(generate_blocks(G, 2)));
// returning just r throws away our state, this should be reworked
// using OOP
// return r;
return {r, G};
};