The C++ rand() function is an Linear Congruential Generator (LCG) PRNG. my questions are:
- Why was this algorithm chosen?
- What are the pros and cons?
- Is it good for cryptography?
Cryptography Stack Exchange is a question and answer site for software developers, mathematicians and others interested in cryptography. It only takes a minute to sign up.
Sign up to join this communityThe C++ rand() function is an Linear Congruential Generator (LCG) PRNG. my questions are:
The C++ rand()
function (actually C function) is not (intended | designed | standarized) for Cryptographic purposes.
- Why was this algorithm chosen?
As SEJPM noted in the comments, the rand function comes from C and C++ has no upper restriction for the implementation.
- What are the pros and cons?
- Is it good for cryptography?
Long story short answer; don't use it for cryptography. For cryptographic purposes use /dev/urandom
The good; it is fast and small. The bad; it is deterministic, and the seed is small ( as noted by poncho in the comments) that prevents it from producing a cryptographically secure RNG from LCG.
/dev/urandom is the best approach to generate a seed for cryptography, but sometimes we need a secure deterministic PRNG in order to compute its sequence in two sides using the same /dev/urandom; I'm talking about CSPRNG (Cryptographically Secure Pseudo Random Number Generators). My advice is to look at a Salsa20 implementation (eg. Chacha20). Those are cryptographycally secure algorithms and probably the best you can find. Another options for cryptographic purposes are the following: Blum-Micali, ISAAC, Yarrow and Fortuna. Perhaps we'd like to discuss about which one is the faster among the CSPRNG.