Skip to content

Instantly share code, notes, and snippets.

@craigfrancis
Created January 6, 2018 12:28
Show Gist options
  • Save craigfrancis/1927645aebe95c03f2ed71495a5f207c to your computer and use it in GitHub Desktop.
Save craigfrancis/1927645aebe95c03f2ed71495a5f207c to your computer and use it in GitHub Desktop.
Why you need to be careful when using base64 encoding to get a random key from random_bytes()
<?php
$characters = [];
for ($k = 0; $k < 500000; $k++) {
$key = base64_encode(random_bytes(32)); // 32 bytes results in "=" padding; try changing to 30 to fix.
foreach (str_split($key) as $c) {
if (!isset($characters[$c])) {
$characters[$c] = 0;
}
$characters[$c]++;
}
}
$characters = array_filter($characters, function($value) {
return ($value > 343750); // ((((33/3)*4)*500000)/64) = 343750, everything else is about ~327000
});
ksort($characters, SORT_STRING);
print_r($characters);
// For 32:
// 0 = 358332
// 4 = 359777
// 8 = 360089
// A = 359424
// E = 358689
// I = 360217
// M = 359899
// Q = 360058
// U = 359104
// Y = 359601
// c = 358607
// g = 358158
// k = 359594
// o = 359204
// s = 358803
// w = 359793
// = = 500000 *
// For 31:
// A = 445603
// Q = 445572
// g = 445780
// w = 445876
// = = 1000000 *
?>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment