Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Bitwise Operations On Large Strings In PHP

Here's my problem. I'm currently trying to implement a few Cryptography standards in PHP for compatibility reasons. The one I'm working on now is SHA256 and SHA512. They are both reasonably straight forward standards, and I'm not having an issue with that.

However, SHA512 requires bitwise operations on 64 bit integers. Since PHP can have only 32 bit integers (with the compile), that leaves me with a problem. How do I implement the bitwise functions necessary (modulo, shift, rotate, add, xor, and, or, etc) so that I both maintain compatibility and a reasonable level of performance...

I know for some of them implementing the functions is trivially done with 2 32 bit ints. However, how will that work for shift and rotate?

What I've thought of doing is storing the strings in binary form (as a string of 01010). That way all bitwise operations will be completely architecture independent. But this will likely cause a massive performance drop since they are used incredibly frequently in the standards (and in other parts of the library).

So my question is thus: How can I easily allow for at least 64 bit string operations in a 32 bit compile of PHP while still maintaining a reasonable level for performance for every step...?

Oh, and my aim is portability here, so no extensions. Other libraries I'll consider, but they must be portable...

like image 221
ircmaxell Avatar asked Apr 04 '11 11:04

ircmaxell


1 Answers

Storing the values in strings is really the right way to go.

But instead of storing 1's and 0's, just store 8 bits in every byte. It will still be easy to extract parts of the integer from your string. You do need to manually do all operations such as shifting.

like image 54
Evert Avatar answered Oct 11 '22 11:10

Evert