php random_bytes and padding
Dear members,

hello. i am obviously new here and i am also new to programming php. I know very little about security and i am hoping to learn more. I found this forum while searching Google for security forums because i have a question about random_bytes.

i notice that whenever i wish to create a random string of say, 16 characters, then i write random_bytes(16). I get what i expect: 16 characters outputĀ  but it is utf-8 (i think), so this could be 14 characters or 15 characters. I think that this is because some characters need an extra byte for storage?

now if i use bin2hex(random_bytes(12)) then the output is 32 characters, so 16x2. Is this because hex requires two bytes?

now if i use base64_encode(random_bytes(16)) the output is 22 characters plus 2 equals signs (+8)(so 16/2).
i am stupid, okay, but i think that this is because 64 is 32x2 so but 24 characters is not 16x2 so how is this working?

now the real question is this: i decied to get an exact output of 16 characters so if 16/2 is 8, then 8/2 is 4, so 16-4 - 12. Thus, i type random_bytes(12) to get 16 characters without an equals sign. Is this secure? am i screwing up here? I'm sorry but i don't understand why this calculated as such. I've read that the equals signs are padding but why is there padding? is padding a zero?

maybe someone can clarify this matter. i just want a random string of 16characters but not binary output, so i use base64_encode and reduce the random bytes to end up with a prettier string of 16 characters. is this okay?

Possibly Related Threads…
Thread Author Replies Views Last Post
  Question for my PHP people out there. 0xRar 4 22,171 12-25-2020, 10:05 PM
Last Post: MuddyBucket
  Finding vulnerabilities in PHP scripts Insider 7 49,833 10-12-2018, 05:31 PM
Last Post: Insider
  PHP Programing Books Lumi 3 29,265 08-22-2016, 09:32 PM
Last Post: Vector
  High Performance PHP Lumi 0 18,417 08-21-2016, 10:39 PM
Last Post: Lumi