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
相关问题
- Views base64 encoded blob in HTML with PHP
- Laravel Option Select - Default Issue
- PHP Recursively File Folder Scan Sorted by Modific
- Can php detect if javascript is on or not?
- Using similar_text and strpos together
This was a really interesting problem (how to create the decimal representation of an arbitrary-length random number in PHP, using no optional extensions). Here's the solution:
Step 1: arbitrary-length random number
At this point, calling
random_bits(2048)
will give you 2048 random bits as a hex-encoded string, no problem.Step 2: arbitrary-precision base conversion
Math is hard, so here's the code:
This function will work as advertised, for example try
base_convert_arbitrary('ffffffffffffffff', 16, 10) == '18446744073709551615'
andbase_convert_arbitrary('10000000000000000', 16, 10) == '18446744073709551616'
.Putting it together
Are you building an OAuth adapter yourself? If so, you might want to reconsider. There are plenty of good OAuth libraries out there, including one from PECL, one in PEAR, another from the Zend Framework, and this other one hosted on Google Code. I've worked with the first three, and they're all pretty decent.
If you really want to do this yourself, you may face an issue. PHP can't think in 64-bit numbers unless it's compiled on a 64-bit platform or you have an advanced mathematics extension installed. This is going to make presenting a 64-bit number as a decimal very difficult. It looks like many of the libraries I linked above completely ignore the format requirement and simply work with a raw MD5 hash. Here's the code from ZF's adapter:
They look like they're getting away with this without interoperability issues.
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
safestsimplest 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().