I have a script that creates a secure token for browser login remember-me like so:
$token = random_bytes(32);
This is then saved to a database for comparison later on:
$sql = " INSERT INTO auth_tokens (user, user_email, auth_type, selector, token, expires_at) VALUES (?, ?, 'remember_me', ?, ?, ?) ";
$stmt = mysqli_stmt_init($conn);
$hashedToken = password_hash($token, PASSWORD_DEFAULT);
// ... more param definitions
mysqli_stmt_bind_param($stmt, $s, $username, $email, $selector, $hashedToken, $date);
mysqli_stmt_execute($stmt);
The problem with this is that random_bytes()
sometimes generates a null character, which then causes password_hash()
to throw an error. I believe this fatal ValueError was added to Bcrypt recently.
PHP Fatal error: Uncaught ValueError: Bcrypt password must not contain null character in *** Stack trace:***: password_hash() {main} thrown in ***
What would be the correct way to prevent null chars generated by random_bytes()
? Does it make sense to simply str_replace('', '', $token)
?
1