Search code examples
securityboost-random

How to generate a secure session id


for a C++ Web-Server I have to generate session id's. I thought of using some kind of random number and hash that with the initial IP address of the session and maybe a timestamp.

Will this yield a reasonable unguessable ID? What would be a good random generator algorithm (most preferable one implemented by boost-random)?

kind regards Torsten

My solution now looks like:

std::string secure_session_generator::operator()( const char* /* network_connection_name */ )
{
    std::stringstream out;
    out << std::hex << distribution_( generator_ );

    return out.str();
}

with the members are default constructed:

    boost::random::random_device                                        generator_;
    boost::random::uniform_int_distribution< boost::uint_least64_t >    distribution_;

Solution

  • You could use the example here: Boost example. Then just increase the size to something more befitting a session id like 64 characters or somethings. That way you don't have to use computation on hashing or anything, and it's already readable.

    Or without using boost-random and just using ctime and stdio.h

    string getRandom(int ip)
    {
        srand(time(NULL) + ip + rand());
        stringstream ss;
        for(int i = 0;i < 64;i++)
        {
                int i = rand() % 127;
                while(i < 32)
                        i = rand() % 127;
                ss << char(i);
        }
        return ss.str();
    }
    

    Alternatively, without using an IP, you could just pump back a rand() in place of IP, just make sure you seed srand with something.

    Also, by all means, I am not a cryptographer, so use are your own risk.