user1560834
user1560834

Reputation: 151

Preventing SQL injection - but without parameters

I've got some code in C# that is being used to create a new password:

SqlCommand cmd = new SqlCommand("select pwdencrypt('" + txtNewPass1.Text + "')", Conn);

Now, this takes our text value from the textbox txtNewPass1 and uses the pwdencrypt to encrypt it, before another bit of code puts it into the database (that bit uses parameters).

However, problem is that the above code doesn't - and actually doesn't seem to be able to. Using a parameter (rather than the txtNewPass1.Text) seems to bring back a wrong value for some reason (actually, I'm wondering now whether I could solve this by putting txtNewPass1.Text into a string, then passing that through a parameter). Using a parameter, at least in this case, gives us a password that doesn't match our value.

Anyone else come across this one before?

Upvotes: 0

Views: 831

Answers (2)

Marc Gravell
Marc Gravell

Reputation: 1062502

sing a parameter (rather than the txtNewPass1.Text) seems to bring back a wrong value for some reason

You should use a parameter unless it is absolutely impossible to do so; any "wrong value" is most likely the difference between varchar and nvarchar - so be careful you know which you want, and which you are using (pwdencrypt('foo') is not the same as pwdencrypt(N'foo')). Also; consider hashbytes rather than pwdencrypt.

Upvotes: 5

user1560834
user1560834

Reputation: 151

D'oh! Don't really want to answer this myself as I'm too embarassed, but hey-ho...

SqlCommand cmd = new SqlCommand("select pwdencrypt(@MyPass)", Conn

I was leaving the single quotes in so it was trying to encrypt ('@MyPass'), rather than (@MyPass). So each time it was encrypting @MyPass as the password, rather than what @MyPass represented as it treated it as a string.

Ignore me, it's too early in the morning. Hmm... nearly lunch time...

Upvotes: 4

Related Questions