jack
jack

Reputation: 155

Cryptographically secure and unique string in PHP

I've been using

$string = bin2hex(openssl_random_pseudo_bytes(16)) . uniqid();

Because I need some string that is both crytopgrahically secure and unique. Question is: is this a naive approach? By using the result of uniqid() tacked onto the end of the string,am I giving away any information that might compromise the security of the string? I ask this because uniqid() is based on system time, and my concern is whether that could give any information away that allows an attacker to guess future outputs?

Thanks

Upvotes: 2

Views: 1023

Answers (2)

Savan Gadhiya
Savan Gadhiya

Reputation: 305

You should use one from the following to generate crytopgrahically secure unique string/number,

  1. bin2hex(openssl_random_pseudo_bytes(16, TRUE)); // Refer manual - (PHP 5 >= 5.3.0, PHP 7)
  2. bin2hex(random_bytes(16)); // Refer manual - (PHP 7)
  3. If you want to generate random number, you can use random_int(100, 999) // Refer manual - (PHP 7)

Upvotes: 2

BeetleJuice
BeetleJuice

Reputation: 40896

Why are you tacking uniqid to it? why not just use the first function?

With 16 bytes, there are about 34 followed by 38 zeros possibilities. For almost any application, the risk of collision is negligible. I would stick to just

bin2hex(openssl_random_pseudo_bytes(16))

From the manual:

If you need a cryptographically secure value, consider using random_int(), random_bytes(), or openssl_random_pseudo_bytes()

Upvotes: 1

Related Questions