Skip to content

Instantly share code, notes, and snippets.

@codeniko
Created May 16, 2014 03:28
Show Gist options
  • Save codeniko/bbb75ed1ae3b0208540c to your computer and use it in GitHub Desktop.
Save codeniko/bbb75ed1ae3b0208540c to your computer and use it in GitHub Desktop.
Create random password keys of argument length
#include <stdlib.h>
#include <chrono>
#include <iostream>
#include <random>
#include <string>
#include <sstream>
#define NUMKEYS 71
static char keys[] = {'a', 'b', 'c' ,'d' ,'e' ,'f' ,'g' ,'h' ,'i' ,'j' ,'k' ,'l' ,'m' ,'n' ,'o' ,'p' ,'q' ,'r' ,'s' ,'t' ,'u' ,'v' ,'w' ,'x' ,'y' ,'z' ,'A' ,'B' ,'C' ,'D' ,'E' ,'F' ,'G' ,'H' ,'I' ,'J' ,'K' ,'L' ,'M' ,'N' ,'O' ,'P' ,'Q' ,'R' ,'S' ,'T' ,'U' ,'V' ,'W' ,'X' ,'Y' ,'Z' ,'0' ,'1' ,'2' ,'3' ,'4' ,'5' ,'6' ,'7' ,'8' ,'9' ,'!' ,'@' ,'#' ,'$' ,'%', '^', '&', '-', '_'};
void generate(int keyLen)
{
unsigned seed = std::chrono::system_clock::now().time_since_epoch().count();
std::mt19937 eng(seed);
//std::default_random_engine eng;
std::uniform_int_distribution<int> dist(0,NUMKEYS-1);
std::stringstream buffer;
for (int bufpos = 0; bufpos < keyLen; ++bufpos) {
buffer << keys[dist(eng)];
}
std::cout << buffer.str() << std::endl;
}
inline void usage()
{
std::cerr << "Usage: keygen <key length>" << std::endl;
}
int main(int argc, char **argv)
{
if (argc == 2) {
int keyLen = strtol(argv[1], NULL, 10);
if (keyLen > 0)
generate(keyLen);
else
usage();
} else if (argc == 1)
generate(15);
else {
usage();
return 1;
}
return 0;
}
CFLAGS=-W -Wall -g -std=c++11 -Wextra -pedantic
keygen: keygen.o
g++ $(CFLAGS) -o keygen keygen.o
keygen.o: keygen.cpp
g++ $(CFLAGS) -c keygen.cpp
.PHONY: clean
clean:
rm -f keygen keygen.o
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment