5

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_;
Torsten Robitzki
  • 3,041
  • 1
  • 21
  • 35

1 Answers1

4

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.

Trickfire
  • 443
  • 2
  • 5
  • I just went to test this myself, and ran into a bunch of problems with versioning on the Boost random library, you shouldn't have an issue if you use the newest one (I would hope). But if you don't want to use the boost random library you could implement this fairly simply by using rand() and srand() to generate numbers and mod them down to readable values (assuming that's a restraint), it may not be the most 'secure', but that really depends on how much you really need. – Trickfire Jul 02 '12 at 09:42
  • i'm going to use the boost solution, as I've heard that the std::rand() implementations might be not usable for such purposes. Thanks for your answer. – Torsten Robitzki Jul 02 '12 at 10:36
  • You would be correct, some rand() implementations cycle rather poorly, and using a mod can skew your distribution slightly, not to mention seeding with the time can bring down possible seed values dramatically. It all depends on how truly random you need it to be. – Trickfire Jul 02 '12 at 10:50