Search code examples
phpsecuritypasswordssha256password-hash

Can I store sha256 hashed passwords in plain text?


So I have php code which saves a hashed version of a password to a file called passwords.txt. As it currently stands, anyone who knows the directory of the file (www.example.com/datacache/passwords.txt) can access it. Is this the incorrect way of doing it? I thought I followed the guide to correct password treatment to the letter, but this seems oddly insecure. Thoughts? Suggestions?

Thank you!


Solution

  • Actually there are two questions here:

    1) Is it ok to store the hashes in a file

    Saving passwords in a file is not better or worse than storing it in a database. The point with a file is, that it should be stored outside of the WWW root directory. Most providers offer a private directory, which can be accessed by code, but canot be reached for HTTP requests.

    2) Is it safe to use SHA-256 for hashing passwords

    No SHA-* and MD5 should not be used directly to hash passwords, because they are too fast and therefore can be brute-forced too easily. Instead one should use a slow function like BCrypt, PBKDF2 or SCrypt, they offer a cost factor and add a safe salt automatically.

    PHP offers a password API with two functions password_hash() and password_verify(). Use them, they are future proof and will produce BCrypt hashes.

    // Hash a new password for storing in the database.
    // The function automatically generates a cryptographically safe salt.
    $hashToStoreInDb = password_hash($password, PASSWORD_DEFAULT);
    
    // Check if the hash of the entered login password, matches the stored hash.
    // The salt and the cost factor will be extracted from $existingHashFromDb.
    $isPasswordCorrect = password_verify($password, $existingHashFromDb);
    

    If you're running an old version of PHP that doesn't have this API, upgrade. If for some reason you can't, check out password_compat.