Understanding SQL Injections

A video version of this article
Query to create user table
Query to insert users and hashed passwords
Login form for application
Dim sqlCommand as SqlCommandDim username As String
Dim password As String
username = usernameTextbox.Text
password = passwordTextbox.Text
sqlConnection.Open()
sqlCommand = New SqlCommand("SELECT COUNT(*) FROM Users WHERE Username = '" & username & "' AND userPassword = HASHBYTES('SHA1','" & password & "')", sqlConnection)
If sqlCommand.ExecuteScalar() > 0 Then
MsgBox("Login Successful")
Else
MsgBox("Login Failed")
End If
User inputs credentials
SELECT COUNT(*) FROM Users
WHERE Username = 'test1'
AND userPassword = HASHBYTES('SHA1','password')
User inputs ‘ as username
SELECT COUNT(*) FROM Users
WHERE Username = '''
AND userPassword = HASHBYTES('SHA1','password')
SQL exception for query
Malicious user input
SELECT COUNT(*) FROM Users 
WHERE Username = ''
OR 1 = 1 -- '
AND userPassword = HASHBYTES('SHA1','notapassword')
User is given access
Dim sqlCommand As SqlCommandDim query As String = "SELECT COUNT(*) FROM Users WHERE Username = @username AND userPassword = HASHBYTES('SHA1',@password)"Dim username As String
Dim password As String
username = usernameTextbox.Text
password = passwordTextbox.Text
sqlConnection.Open()sqlCommand = New SqlCommand(query, sqlConnection)sqlCommand.Parameters.Add("@username", SqlDbType.VarChar, 300).Value = usernamesqlCommand.Parameters.Add("@password", SqlDbType.VarChar, 300).Value = passwordIf sqlCommand.ExecuteScalar() > 0 ThenMsgBox("Login Successful")ElseMsgBox("Login Failed")End If
User is now rejected access

Computer programmer specializing in security. My blog: www.scprogramming.com

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store