Search code examples
mysqldatabasehashsql-injection

Hashed password must be sanitized?


It's just a curiosity. If you encrypt a password (using sha1 or other methods) before inserting it in a query, it must be anyway sanitized? Or the hash's result is always safe?

This simple code are safe?

$salt = "123xcv";
$password = $_POST['password'];
$password = sha1($password+$salt);

$query = "select * from user where password='$password'";

Solution

  • Unless you validated the input somehow you shouldn't assume that it will always return a safe output because functions such as SHA1 can return error values if given unexpected input. For example:

    echo '<?php echo sha1(''); ?>' | php 
    Warning: sha1() expects at least 1 parameter, 0 given in - on line 1
    

    And this output obviously violates the assumption that "it's always a hex string". Other hashing functions in other languages can present yet another behaviour.

    Apart from that, the above password hashing code scheme ($password = sha1($password+$salt);) is very weak (see why) and I would strongly recommend not using it even in an example as someone is eventually guaranteed to find it on StackOverflow and use in production.

    Also, as already noted above, building SQL queries by concatenating strings is also a bad practice and can lead to security issues in future: today the only parameter in the query will be the password, tomorrow someone decides to add some other option and I bet they won't rewrite the query but just use the template that is already there...