Generating random passwords is one of the initial exercises for anyone who wants to advance in system security. We have already written an article explaining how you can generate passwords, for more details read the full post: 23 Ways to Generate and Save STRONG PASSWORDS; see command explanations.
In this article we will learn about the logic of generating passwords with C++. It will be a simple code using only alphanumeric passwords, but you can improve it by adding special characters to make the code even more complete.
Let’s go step by step!
In this example, we will organize our code so that if we want to add it to a project in the future, we will create a “header-only” (just one file: .hpp
), that is, the class and the execution in the same file:
vim genpass.hpp
#02. Adding the content Let’s now add 2 private members to use in our member function, they are:
std::string pass
- Which will store the string that will be returned to the object;const std::string charset
- The constant that will contain alphanumeric characters, both lowercase and UPPERCASE, in addition to numbers;#03. Add the member function that will return our password This member function will receive the length of the password as an argument, you could choose a default minimum value, but I will leave any length possible, but it is good to remember that strong passwords have at least 8 characters!
charset
characters randomly;pass
member until reaching the maximum specified in the argument;#04. Final genpass.hpp
file
In the end, our complete file will look like this:
Let’s create a new file main.cpp
and include our genpass.hpp
, and call the member function gen_pass()
with the number of characters we want our password to have, in this example: Generating an alphanumeric password with 8 characters!
Compile and run:
g++ main.cpp && ./a.out
. Probable and similar output:
If you want to generate with: 16, 32, 64 and 128 characters, respectively:
Simple and easy, right?! Now you can use this unique header and add it to your projects!