I am trying to code a random string generator using boost libraries for random number generation. I have tried coding the same keygen without using boost and relying on normal PRNG with a time seed.
// keygen.cpp : Defines the entry point for the console application.
//
#include "stdafx.h"
#include <iostream>
#include <ctime>
#include <string>
#include <boost/random/mersenne_twister.hpp>
#include <boost/random/uniform_int.hpp>
#include <boost/random/variate_generator.hpp>
#include "md5wrapper.h"
usingnamespace std;
usingnamespace boost;
int _tmain(int argc, _TCHAR* argv[])
{
//Define keyspace
//string alpha="abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890";
string alpha="ABCDEFGHIJKLMNOPQRSTUVWXYZ";
//Setup random number generator
static mt19937 generator(static_cast<unsignedint>(std::time(0)));
uniform_int<> uni_int_dist( 0, alpha.length() );
variate_generator< mt19937&, uniform_int<> > r( generator, uni_int_dist );
//hash init
md5wrapper md5;
//initialize keygen
int n = 10; // key length
int count = 0;
//timing
clock_t start,finish;
double time;
start = clock();
while (1) {
//generate key
char *key = newchar[n+1];
for(int i=0;i<n;i++)
key[i] = alpha[r()];
key[n] = '\0';
//generate md5 hash
string hash = md5.getHashFromString(md5.getHashFromString(string(key,n)));
//output status
if(((count++)%10000) ==0 )
{
time = (double(clock())-double(start))/CLOCKS_PER_SEC;
cout<<count<<'\t'<<time<<'\t'<<key<<'\t'<<hash<<endl;
}
//look for a target hash
if (hash=="2c4972c770836eaf3b237a561b06daaa")
{
cout<<key<<'\t'<<hash<<'\n';
getchar();
}
delete [] key;
}
return 0;
}
As per the code it should generate random strings of size n, and compute its md5 hashes. However, when running the code, it sometimes generates smaller strings or even empty strings. I do not understand why that is happening..
I might be misinterpreting what you are trying to do, but couldn't you just generate a random number between 0 and 25, then get a particular character from the vector of characters, and push_back it into the string?
while(String.size() < 25) {
char temp = rand_int('a','z'); //get a random char from a - z into temp (no this function doesn't exist normally)
String.push_back(temp);
}
if you are worried about string size, i would suggest using firedraco's code above, and just replacing the '25' in the while statement with a random number between your string size's min/max.