Boost C++ Libraries Home Libraries People FAQ More

PrevUpHomeNext

Generating a random password

For the source of this example see password.cpp.

This example demonstrates generating a random 8 character password.

#include <boost/random/random_device.hpp>
#include <boost/random/uniform_int_distribution.hpp>

int main() {
    1std::string chars(
        "abcdefghijklmnopqrstuvwxyz"
        "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
        "1234567890"
        "!@#$%^&*()"
        "`~-_=+[{]}\\|;:'\",<.>/? ");
    2boost::random::random_device rng;
    3boost::random::uniform_int_distribution<> index_dist(0, chars.size() - 1);
    for(int i = 0; i < 8; ++i) {
        std::cout << chars[index_dist(rng)];
    }
    std::cout << std::endl;
}

1

We first define the characters that we're going to allow. This is pretty much just the characters on a standard keyboard.

2

We use random_device as a source of entropy, since we want passwords that are not predictable.

3

Finally we select 8 random characters from the string and print them to cout.


PrevUpHomeNext