Skip to main content

Generating Credentials: secure data sources

If you have a use case where you need to give a user a one-time password or key to authenticate for something, you need to make sure that key or password has been securely generated. A common example of this would be for activation codes sent in emails to veirfy a user owns their email address, or recovery codes for users who lose their 2FA device.

Only generate one-time credentials with secure data streams

Where randomness is concerned, there are two types of "random" values: pseudorandom values, which are sufficiently random for normal things where you want a random value but are not cryptographically secure, and true random values which are usually used for cryptographically secure purposes.

Here are some examples of pseudorandom and true random values in different languages.

PHP
// Pseudorandom integer value: NOT cryptographically secure
$pseudoRandom = rand();

// True random string of 64 bytes: cryptographically secure
$trueRandom = random_bytes(64);
Java
// Returns a double between 0.0 and 1.0: NOT cryptographically secure 
double pseudoRandom = java.lang.Math.random();

// Returns 64 random bytes: crytographically secure.
SecureRandom random = new java.security.SecureRandom();
byte[] secureRandombytes = new byte[64];
random.nextBytes(secureRandombytes);

When generating secure credentials, such as activation codes, be sure to generate them by using cryptographically secure random values, and not pseudorandom values.