I have a code like this:
$alphabet = array('0','1','2','3','4','5','6','7','8','9','a','b','c','d','e','f','g','h','i','j','k','l','m','n','o','p','q','r','s','t','u','v','w','x','y','z');
$alphabetSize = count($alphabet);
$alphabetBitSize = ceil(log($alphabetSize, 2));
$bitSize = $length * $alphabetBitSize;
$bytes = random_bytes(ceil($bitSize/8));
What I need is reading $bitSize
bits in a loop to generate a latin1 string using the alphabet. Now I am totally lost about how to do this with the $bytes
I have. Most of the answers are using string functions to do this, but I guess I need something binary. Another option is doing it with hex maybe. Any hints?
3
Answers
I wrote my own code with bin2hex
I generally will use PHP’s built-in function
unpack()
to convert the bytes into a hexadecimal string and then to a binary string. I hope this helps.To generate a string from the random bytes in a loop, you can use bitwise operations to extract the necessary bits from the byte sequence. You can try the code bellow:
In this example, I used the ord function to get the ASCII value of a character from the random bytes. Then, performed bitwise shifting and masking to extract each bit. The resulting bit is used to index the alphabet array to form the final string.
Let me know it this works for you..