Search code examples
phprandomoautharbitrary-precision

How to generate random 64-bit value as decimal string in PHP


Oauth requires a random 64-bit, unsigned number encoded as an ASCII string in decimal format. Can you guys help me achieve this with php? Thanks


Solution

  • You could use two 32-bit numbers, four 16-bit numbers, etc.

    PHP has rand() and and mt_rand() but how many random bits they supply isn't specified by the standard (though they can be queried with the help of getrandmax() and mt_getrandmax(), respectively.)

    So your safest simplest bet would be generating 64 random bits and setting them one by one.

    As for working with 64-bit integers, I'd recommend using the GMP library as it has a good range of functions to help you out.

    You could create a number, call 64 gmp_setbit()s on it with successive positions then convert it to a string using gmp_strval().