Search code examples
crandomsrandrandom-seed

Srand with char array in C?


How can I random seed with a char array instead of an int in C?
I want to use a password, not a number, but srand only takes integers.
Is there a way to do this?


Solution

  • Just use a hash function. A classic is hash_pjw,

    unsigned hash_pjw (const void *str)   
    {
      const char *s = str;
      unsigned int g, h = 1234567u;
      while (*s != 0) {
        h = (h << 4) + *s++;
        if ((g = h & (unsigned int) 0xf0000000) != 0)
           h = (h ^ (g >> 24)) ^ g;
      }
      return h;
    }
    

    Note that rand() is nothing like cryptographically secure.