Home > Software design >  Can SQL be injected when the input is hashed?
Can SQL be injected when the input is hashed?

Time:05-07

The passwords and my SQL database are hashed. If the input is hashed, can the field be injected? The hash is SHA256. My command is to be:

SELECT true FROM accounts WHERE password = '[hex digits]';

CodePudding user response:

I suggest that you not ask this question, because maybe there is a way that you can be in danger, but probably there isn't. Instead, use SQL placeholders and bind variables because that's why they exist.

Any time you are building a SQL statement using data that you are not directly controlling, you are running a risk.

Prepared SQL statements with placeholders also have the benefit of being less work for the database.

Do you have a reason that you can't do it this way?

CodePudding user response:

Strictly speaking, the example you give is safe. Similarly, if you have an application variable that can only be an integer, it is safe. Or even if it's a string, if your code is in control of the string, and you can be sure the string doesn't contain characters that would cause SQL injection (e.g. quote characters like ' or "), then it's safe.

But I agree with Andy Lester's answer — just use query parameters, and then you don't have to think about it. You don't have to wonder if there's an edge case where the input string may be out of your control. You don't have to ask if a string of hex digits is safe or not.

And even more importantly, you don't have to worry that not every developer on your team has the same understanding of how to tell if an input is safe or not. Many developers don't know how to tell safe inputs from non-safe inputs, so it's safest to just establish a policy that all inputs must be parameterized into an SQL query after it is parsed, instead of concatenated into the SQL query before it is parsed.

Imagine you are an electrician. You don't want to touch a live circuit, but if you're well trained you know if you touch it with the right kind of insulated protection, or if you're not grounded, or other conditions are true, then you're probably safe. Probably.

But what is safest is to just make sure the circuit has been disconnected from the power source. That's just a smart habit. It always works, and even if you work with other people who are not as smart as you, it still works.

  • Related