Skip to main content

You are not logged in. Your edit will be placed in a queue until it is peer reviewed.

We welcome edits that make the post easier to understand and more valuable for readers. Because community members review edits, please try to make the post substantially better than how you found it, for example, by fixing grammar or adding additional resources and hyperlinks.

Required fields*

6
  • 1
    This will not generate a string with the given length Commented Feb 19, 2020 at 8:39
  • getRandomBytes() (all of them, really) only works for even lengths. Other than that, one of the better, less-scary answers here. Commented Sep 24, 2021 at 6:07
  • @DewiMorgan, I guess any hashing algo generates even length. Commented Sep 25, 2021 at 3:32
  • Well, it's more that bin2hex() specifically will inevitably return an even number of hex chars. Truncating the output by one char for odd-length cases shouldn't, so far as I can tell, affect the entropy... but I admit it'd add a few extra lines to the code that would be pointless for almost all use-cases. Commented Sep 25, 2021 at 3:55
  • So $odd=$length%2; $length+=$odd; at the beginning, and return substr(bin2hex($length), $odd); at the end would do the trick... but at the cost of considerable readability. Yours is cleaner and more maintainable, so I'd probably just add a comment about the "only even lengths" caveat if I were to use it, unless it truly mattered. Commented Sep 25, 2021 at 4:03