Skip to content

Instantly share code, notes, and snippets.

@zenware
Created May 21, 2013 12:14
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 zenware/5619378 to your computer and use it in GitHub Desktop.
Save zenware/5619378 to your computer and use it in GitHub Desktop.
One man's quest for the most optimized random password generator that can be made with C++, hopefully this will be useful.
#include <chrono>
#include <functional>
#include <iostream>
#include <random>
#include <string>
static void show_usage(std::string name)
{
std::cerr << "Usage: " << name << " <option(s)>\n"
<< "Options:\n"
<< "\t-h,--help\t\tShow this help message\n"
<< "\t-l,--length LENGTH\tSpecify the password length\n"
<< "\t-s,--seed SEED\t\tUse a unique seed for the random engine\n"
<< "\t-v,--version\t\tOutput the program version\n";
}
int main (int argc, char *argv[])
{
std::string charset ("abcdefghijklmnopqrstuvwxyz"
"ABCDEFGHIJKLMNOPQRSTUVWXYZ"
"1234567890!@#$%^&*()");
int length = 16;
std::default_random_engine generator;
std::uniform_int_distribution<int> distribution (0, (int) charset.size() - 1);
generator.seed (std::chrono::system_clock::now().time_since_epoch().count());
if (argc >= 2) {
for (int i = 1; i < argc; i++) {
std::string arg = argv[i];
if ((arg == "-l") || (arg == "--length")) {
if (i + 1 < argc) {
length = atoi(argv[++i]);
} else {
std::cerr << "-l,--length takes one argument" << std::endl;
return 1;
}
} else if ((arg == "-s") || (arg == "--seed")) {
if (i + 1 < argc) {
std::string str (argv[++i]);
std::seed_seq seed (str.begin(), str.end());
generator.seed (seed);
} else {
std::cerr << "-s,--seed takes one argument" << std::endl;
return 1;
}
} else if ((arg == "-h") || (arg == "--help")) {
show_usage(argv[0]);
return 0;
} else if ((arg == "-v") || (arg == "--version")) {
std::cout << "Version 0.0.1" << std::endl;
return 0;
}
}
}
auto randchar = std::bind (distribution, generator);
std::string password;
password.resize(length);
for (int i = 0; i < length; i++) {
password.at(i) = charset.at(randchar());
}
std::cout << password << std::endl;
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment