Blog | G5 Cyber Security

BCrypt Differences: Base64 Encoding

TL;DR

Different BCrypt implementations (e.g., Python’s bcrypt library vs. PHP’s) may produce slightly different output hashes even with the same password and salt. This is often due to internal string encoding differences. To compare these hashes reliably, Base64 encode them before comparison.

Solution Guide

  1. Understand the Problem: BCrypt uses a salt to add randomness to passwords before hashing. Different programming languages and libraries handle strings (including salts) in slightly different ways. This can lead to variations in the final hash, even if everything else is identical.
    • These differences are usually small but enough to cause comparisons to fail.
    • Base64 encoding provides a standard way to represent binary data as text, making comparison easier across platforms and languages.
  2. Identify Your BCrypt Implementations: Determine which libraries or functions you are using for BCrypt hashing.
    • Examples include Python’s bcrypt library, PHP’s password_hash() and password_verify() functions, Node.js’s bcryptjs package, etc.
  3. Hash the Password with Each Implementation: Generate a BCrypt hash using each implementation with the same password and salt.

    For example:

    • Python (bcrypt):
      import bcrypt
      password = "mysecretpassword"
      salt = b"mysalt"
      hash_python = bcrypt.hashpw(password.encode('utf-8'), salt)
      print(hash_python)
    • PHP (password_hash()):
       10]);
      echo $hash_php;
      ?>
  4. Base64 Encode the Hashes: Use Base64 encoding to convert each hash into a text string.
    • Python:
      import base64
      hash_python_encoded = base64.b64encode(hash_python).decode('utf-8')
      print(hash_python_encoded)
    • PHP:
  5. Compare the Base64 Encoded Hashes: Compare the Base64 encoded strings. They should now match if the underlying BCrypt hashes were generated correctly with the same password and salt.
    • In Python:
      if hash_python_encoded == hash_php_encoded:
        print("Hashes match!")
      else:
        print("Hashes do not match!")
    • In PHP:
  6. Important Considerations:
    • Always use the same salt when generating hashes across different implementations.
    • The ‘cost’ parameter in BCrypt affects hashing speed and security; ensure it is consistent across implementations if possible.
    • Base64 encoding only standardizes the *representation* of the hash, not the hashing process itself. If the underlying algorithms or salt values differ significantly, comparison will still fail.
Exit mobile version