-2
$\begingroup$

Is it possible to attack this construction if the attacker only knows the hash?

sha256( mt_rand()
       .mt_rand()
       .mt_rand()
       .mt_rand()
       .mt_rand()
       .mt_ra‌​‌​nd()
       .mt_rand()
       .mt_‌​ra‌​nd()
       .mt_rand()
       .m‌​t_ra‌​nd()
       .mt_rand()‌​
       .mt_ra‌​nd())

If possible, explain how?

$\endgroup$
1
  • 1
    $\begingroup$ Bruteforcing the seed should work. $\endgroup$ Commented Dec 15, 2017 at 0:17

1 Answer 1

3
$\begingroup$

Yes, it’s possible to attack this construction for a simple reason: the code you show is insecure, because mt_rand is not cryptographically secure. Even worse: you are obviously relying on PHP’s internal seeding of mt_rand – which isn’t cryptographically secure either. [1] [2]

Quoting the related mt_rand page of the PHP manual:

Caution This function does not generate cryptographically secure values, and should not be used for cryptographic purposes. If you need a cryptographically secure value, consider using random_int(), random_bytes(), or openssl_random_pseudo_bytes() instead.

See, mt_rand is a pseudo-random number generating function based on the Mersenne Twister.

Now, calling it 12 times in a row (as your code does) means you are using 12 outputs in sequence, which can be reconstructed rather easy. This could be exploited by bluntly brute-forcing the seed – which would take less time than brute-forcing the SHA-256 function itself. Due to that, your construction has to be considered broken from a cryptographic point of view… which practically means it’s insecure and should not be used.

Last but not least, you can not rely on the fact people don’t know how you coded things. That would be “security through obscurity” which is bound to break your neck. For that reason, cryptographers assume “the enemy knows the system” and adher to Kerckhoffs’ principles – and so should you.

The correct way to do it

Instead of your code, you should be using a cryptographically secure seed of (at least) 32 bytes:

 $securelySeededHash = hash('sha256', random_bytes(32));

The random_bytes function is cryptographically secure and generates an arbitrary length string of cryptographic random bytes that are suitable for cryptographic use, such as when generating salts, keys or initialization vectors. The sources of randomness used for this function are system-native.

$\endgroup$
1
  • $\begingroup$ Comments are not for extended discussion; this conversation has been moved to chat. $\endgroup$
    – e-sushi
    Commented Dec 17, 2017 at 13:34

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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