Convert string to binary then back again using PHP

Convert string to binary then back again using PHP

  1. Blog
  2. 15 November 2026
  3. 3 min read

Stefan Bogdanescu

Founder & Senior Architect

Converting Strings to Binary in PHP: A Practical Guide for Password Storage

Storing passwords as raw text in a database is a security failure, but storing them as binary data requires careful consideration of how that data is handled within your application stack. The standard PHP library provides specific tools to handle this conversion without relying on external extensions or complex third-party libraries. When you need to transform a string into its binary representation and then reverse that process, the goal is often to persist a hashed value—such as a password—in a database column defined as BLOB or VARBINARY.

The most direct approach in standard PHP involves using functions like hash_hmac() combined with base64 encoding. While hash_hmac() generates a binary hash output, databases generally struggle to accept raw binary strings directly from PHP scripts without an intermediate step. This is where the conversion logic becomes critical. You cannot simply pass the raw binary output of hash_hmac into a string variable expecting it to remain intact through serialization or JSON encoding later down the line; the data will corrupt.

The standard pattern for this scenario looks like this:

$plainPassword = 'MySecurePassword123!';
$key = 'my-secret-key'; // Use a securely stored random key, not hardcoded

// Generate the raw binary hash
$binaryHash = hash_hmac('sha256', $plainPassword, $key);

// Convert to base64 for storage as a string in the DB
$storedHash = base64_encode($binaryHash);

By using base64_encode(), you ensure that the binary data remains intact when stored in a text-based column (like TEXT or VARCHAR) or when serialized into JSON. This is functionally equivalent to storing binary data, provided you decode it correctly on retrieval. If your database schema strictly requires a binary type, such as BLOB, you can store the raw output of hash_hmac directly using addcslashes() to escape any special characters that might interfere with SQL injection or string formatting issues, though Base64 remains the safest universal transport format.

Reversing the process is equally straightforward but requires strict adherence to the encoding used during storage. If you stored a Base64 string, you must decode it back into binary before passing it to verification functions:

function verifyPassword(string $inputPassword, string $storedHashString): bool {
    // Decode the stored hash back to raw binary
    $binaryHash = base64_decode($storedHashString);
    
    if ($binaryHash === false) {
        return false; // Invalid Base64 data
    }

    $key = 'my-secret-key';
    
    // Generate a new hash for the input password
    $newHash = hash_hmac('sha256', $inputPassword, $key);
    
    // Constant-time comparison is essential to prevent timing attacks
    return hash_equals($storedHashString ?? base64_encode($binaryHash), base64_encode($newHash));
}

There are significant trade-offs to consider here. Using Base64 adds roughly 33% overhead to the data size compared to raw binary, but it eliminates the risk of database column truncation or character set mismatches that often plague BLOB handling in MySQL or PostgreSQL. Furthermore, relying on standard PHP functions ensures compatibility across virtually all hosting environments without needing to install additional extensions like bcmath or specific cryptographic libraries.

A common pitfall is attempting to compare hashes using the standard equality operator (==). If an attacker can measure the response time of your application, they might deduce parts of the password based on how long it takes for a mismatched byte to be detected versus a match. Always use hash_equals() when verifying passwords. Additionally, never reuse the same HMAC key across different algorithms or contexts; if you switch from SHA256 to SHA512 later, your existing database entries become incompatible unless you migrate them with a new key.

For developers working within the Laravel ecosystem, this logic translates cleanly into model mutators. You can define a $casts property in your Eloquent model to automatically handle the Base64 conversion when accessing password attributes, ensuring that your application layer never deals with raw binary strings directly. This abstraction keeps your codebase clean while maintaining the security rigor required for sensitive data.

Our network