4

When converting "random bytes" to a string, is there any difference as to whether I should use base64_encode or bin2hex?

$bytes = openssl_random_pseudo_bytes(32); // alternatively read from /dev/urandom

echo base64_encode($bytes); // some 44 character string
echo bin2hex($bytes); // some 64 character string

To use as a salt for bcrypt, obviously modified base64 is the correct choice because that is what's expected. But for contexts like account sign-up confirmation key or a unique non-sequential object identifier, which is the correct choice?

I am aware of the random_compat library but this is for learning purposes as well.

rink.attendant.6
  • 44,500
  • 61
  • 101
  • 156

1 Answers1

4

Besides length? Not really. They're both representations of the same data. The choice is up to you.

But keep in mind:

  • Base64 data may include the characters +, /, and =, which may need to be URL encoded.

  • As Base64 data may contain any alphanumeric character, there's a slight chance that it'll contain objectionable words. (This is also technically possible with hex-encoded data, but less common, as it only uses the letters A through F.)