passwdgen/passwdgen.cpp

80 lines
2.4 KiB
C++
Raw Normal View History

//
// passwdgen.cpp
// Created by Greg Gauthier on 2020.10.22.
//
2020-10-22 11:13:08 +00:00
#include <iostream>
#include <random>
2020-10-22 11:13:08 +00:00
std::string random_string(std::size_t length, bool punc) {
std::string CHARACTERS;
std::string ALPHANUM = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz";
2025-09-05 10:59:22 +00:00
const std::string SPECIALS = "!\"#$%&'()*+,-./:;<=>?@[\\]^_`{|}~";
2020-10-22 11:13:08 +00:00
if (punc) {
CHARACTERS = ALPHANUM.append(SPECIALS);
} else {
CHARACTERS = ALPHANUM;
}
2025-09-05 10:59:22 +00:00
2020-10-22 11:13:08 +00:00
std::random_device random_device;
std::mt19937 generator(random_device());
2025-09-05 10:59:22 +00:00
std::uniform_int_distribution<> distribution(0, static_cast<int>(CHARACTERS.size() - 1));
2020-10-22 11:13:08 +00:00
std::string random_string;
for (std::size_t i = 0; i < length; ++i) {
random_string += CHARACTERS[distribution(generator)];
}
return random_string;
}
2025-09-05 10:59:22 +00:00
void show_usage(const std::string& name) {
std::cerr << "Usage: " << name << " [OPTIONS] " << std::endl
2020-10-22 11:13:08 +00:00
<< "Options:" << std::endl
<< "\t-h, --help \t\tShow this help message" << std::endl
<< "\t-l, --length [n] \t\tThe length of the password (default: 32)" << std::endl
2020-10-22 11:13:08 +00:00
<< "\t-p, --punctuation \t\tToggle special characters (default: false)"
<< std::endl;
}
int main(int argc, char *argv[]) {
2025-09-05 10:59:22 +00:00
int passwordLength = 0;
2020-10-22 11:13:08 +00:00
bool punc = false;
if (argc < 1) {
std::cout << random_string(32, false) << std::endl;
return 0;
2025-09-05 10:59:22 +00:00
}
for (int i = 1; i < argc; ++i) {
std::string arg = argv[i];
if ((arg == "-h") || (arg == "--help")) {
show_usage(argv[0]);
return 0;
}
if (arg == "-p") {
punc = true;
} else if ((arg == "-l") || (arg == "--length")) {
if (not argv[i +1]) {
std::cerr << "Specify a password length" << std::endl;
return 1;
}
std::string passwordLengthStr = argv[i + 1];
try {
passwordLength = std::stoi(passwordLengthStr);
} catch ([[maybe_unused]] const std::invalid_argument& e){
std::cerr << "Length must be a valid integer" << std::endl;
return 1;
2020-10-22 11:13:08 +00:00
}
}
2025-09-05 10:59:22 +00:00
}
2020-10-22 11:13:08 +00:00
2025-09-05 10:59:22 +00:00
if (passwordLength == 0) {
passwordLength = 32;
2020-10-22 11:13:08 +00:00
}
2025-09-05 10:59:22 +00:00
std::string password = random_string(passwordLength, punc);
std::cout << password << std::endl;
return 0;
2020-10-22 11:13:08 +00:00
}