7

I am using:

 random_bytes(30);

to generate a random string for my program. This string is then stored in a mysql database. However, when I run the function, I get an output such as

T�Ը�@(���m

which includes unreadable characters. When I then try to store it in my database, the � characters are not stored and so this means that the string is not properly preserved.

How can I make it so that it returns a string with only readable characters that will not be lost in my mysql database?

Thanks!

Onglo
  • 181
  • 1
  • 11
  • 1
    I think some reading about UTF-8 may help you, **but** random bytes??? What were you expecting, the complete works of Shakespear? – RiggsFolly Jul 02 '17 at 18:59
  • Possible duplicate of [PHP random string generator](https://stackoverflow.com/questions/4356289/php-random-string-generator) – Jocelyn Jul 02 '17 at 19:02
  • Possible duplicate of [UTF-8 all the way through](https://stackoverflow.com/questions/279170/utf-8-all-the-way-through) – Jocelyn Jul 02 '17 at 19:05
  • It will serve you well to learn some small ampunt abiuyt charcter encodings, a good place to start is ASCII and then unicode, specifically UTF-8 since that is what is generally used for interchange. – zaph Jul 02 '17 at 19:39
  • The closest thing to what you were trying to do is probably [`Random::asciiPrintableString($length)`](https://github.com/delight-im/PHP-Random). That’s all characters that can be printed or seen on the screen. But if you want to use that random string in a URL, for example, you’d want something like `Random::base64UrlString($length)` instead, with characters that don’t need encoding or escaping in a URL. – caw Nov 22 '19 at 17:17

1 Answers1

8

random_bytes generates an arbitrary length string of cryptographic random bytes that are suitable for cryptographic use, such as when generating salts, keys or initialization vectors. use like this

$bytes = random_bytes(5);
echo bin2hex($bytes);
Your Common Sense
  • 156,878
  • 40
  • 214
  • 345
RAUSHAN KUMAR
  • 5,846
  • 4
  • 34
  • 70
  • Thank you for your help! Can I just check that the string is still cryptographically secure when you bin2hex it? – Onglo Jul 02 '17 at 19:08
  • 8
    While `random_bytes` generates cryptographically secure random bytes `rand` does not. From thr [PHP `rand` page](http://php.net/manual/en/function.rand.php): *Caution: This function does not generate cryptographically secure values*. – zaph Jul 02 '17 at 19:43
  • 2
    Just encoding random bytes does not change the randomness, hex and Base64 are common ebcodings thrat produce ASCIIcharacters. – zaph Jul 02 '17 at 19:45
  • 4
    The example code will produce non cryptographically secure psudo random characters in base 62 which is essentially unsuitable for almost all purposes. – zaph Jul 02 '17 at 19:53