In my web application I generate temporary tokens/passwords for accessing files using this method:

ALPHABET = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789-_"

def generate_token(str_len = 22)
   res = ""
   str_len.times{res << ALPHABET[rand(ALPHABET_LENGTH)]}

Is there any vulnerability in generating tokens/passwords this way?

If it matters, a generated token lives 7 days.


Since it looks like you are using Ruby's default RNG, the Mersenne Twister, it is possible for an attacker to obtain the seed of the RNG, and therefore compromise all past, present, and future numbers generated by the algorithm using something like mt_derand. It is probably a better idea to use SecureRandom instead.

  • While that's strictly true, it's unlikely that all randomness is obtained from a single instance of the RNG, especially on a webserver that probably runs multiple threads or processes.
    – David
    Jan 12 '18 at 0:50
  • 1) it is possible for an attacker to obtain the seed of the RNG, ---> how?
    – Ramito
    Jan 12 '18 at 1:30
  • 2) what should I use instead? secure hash function?
    – Ramito
    Jan 12 '18 at 1:31
  • 1
    If you'd like to use SecureRandom instead of rand, you would just replace str_len.times{res << ALPHABET[rand(ALPHABET_LENGTH)]} with str_len.times{res << ALPHABET[SecureRandom.random_number(ALPHABET_LENGTH)]} and include require 'securerandom' at the top of your code
    – LamerZ
    Jan 13 '18 at 9:56
  • 2
    @Ramito 1) Read the link to mt_derand 2) You should use SecureRandom instead
    – LamerZ
    Jan 14 '18 at 13:30

It depends on the quality of the rand function.

If it's not a secure random number generator (and in particular if it's a standard function from a known framework), then yes: an attacker could analyse a number of sequentially generated tokens and have a good chance of finding out the internal state of the RNG, allowing him to extrapolate a new token from an existing valid one.

  • what should I use instead? secure hash function?
    – Ramito
    Jan 12 '18 at 7:52
  • A secure hash function using a cryptographically secure RNG and a good source of enthropy. e.g. github.com/cryptosphere/sysrandom (I haven't tested or even evalutaed it beyond the projects page but it looks like it's doing things right)
    – Stephane
    Jan 12 '18 at 9:15
  • what my "rand" is implemented using that or similar function already?
    – Ramito
    Jan 14 '18 at 2:57

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.