Please start any new threads on our new site at https://forums.sqlteam.com. We've got lots of great SQL Server experts to answer whatever question you can come up with.

 All Forums
 General SQL Server Forums
 New to SQL Server Programming
 Stored Procedure Issue

Author  Topic 

tvb2727
Starting Member

35 Posts

Posted - 2011-08-03 : 03:47:18
I am making a stored procedure for a login table. I want to validate my password that is hashed with SHA1 and then use the password passed in and the password salt. Right now I am doing a select on my password salt per user name and then adding it to my main password and then passing that to the stored procedure. Is there a way that I can just pass my password in and then let the stored procedure HASH it with SHA1 and then verify it? Here is an example that I found, but I can't get it to work:


CREATE PROCEDURE sp_TestCredentials
(
@UserName NVARCHAR(255) ,
@Password NVARCHAR(255)
)
AS
BEGIN
SELECT UserName
FROM Credentials
WHERE UserName = @UserName
AND PasswordHash = HASHBYTES('SHA1', @Password + PasswordSalt) ;
-- Further control logic (return values) and error handling required.
END ;
GO

tvb2727
Starting Member

35 Posts

Posted - 2011-08-03 : 04:46:54
I tried this and no luck. What am I doing wrong?


ALTER PROCEDURE [dbo].[verify_un_and_pw_quick]
@UN VARCHAR(50) = NULL,
@PW NVARCHAR(128) = NULL



AS

BEGIN


DECLARE @HashThis2 nvarchar(128);
DECLARE @Final nvarchar(128);
SELECT @HashThis2 = (SELECT pws from tbl_login where user_name_27 = @un)

DECLARE @HashThis nvarchar(128);
SELECT @HashThis = CONVERT(nvarchar(128),@PW);
SELECT @Final= HashBytes('SHA1', Convert(nvarchar(128),@HashThis + @HashThis2));


PRINT @Final



SELECT COUNT(*)
FROM [tbl_login]
WHERE (user_name_27 = @UN) AND (pw = @Final) ;
END


Go to Top of Page

visakh16
Very Important crosS Applying yaK Herder

52326 Posts

Posted - 2011-08-03 : 04:56:36
what do you mean you cant get it to work? is it giving some error? more info on that will help. is hashbytes a udf?

------------------------------------------------------------------------------------------------------
SQL Server MVP
http://visakhm.blogspot.com/

Go to Top of Page

tvb2727
Starting Member

35 Posts

Posted - 2011-08-03 : 11:34:45
Even though I pass in my correct password and user name it still returns 0 when it should return 1 - No error at all. Not sure hashbytes is a UDF?
Go to Top of Page

tvb2727
Starting Member

35 Posts

Posted - 2011-08-03 : 15:37:08
When I show it out this is what I see:

??????????
Go to Top of Page

visakh16
Very Important crosS Applying yaK Herder

52326 Posts

Posted - 2011-08-04 : 08:40:26
why are you using NVARCHAR? is it some other language character?

------------------------------------------------------------------------------------------------------
SQL Server MVP
http://visakhm.blogspot.com/

Go to Top of Page

Lamprey
Master Smack Fu Yak Hacker

4614 Posts

Posted - 2011-08-04 : 10:33:02
What data type is PasswordHash? HashBytes returns a varbinary (maximum 8000 bytes). ALthough, you are putting both results into an NVARCAHR(128), so I'd hope the conversion would be the same for both. Can you post some sample data that we can run queries against? This link can help you prepare your DDL and DML:
http://weblogs.sqlteam.com/brettk/archive/2005/05/25/5276.aspx

Go to Top of Page

Lamprey
Master Smack Fu Yak Hacker

4614 Posts

Posted - 2011-08-04 : 10:41:24
Just for fun, I put together a quick sample that works:
DECLARE @Logon TABLE 
(
UserName NVARCHAR(50),
HashedPassword VARBINARY(8000),
ActualPassword NVARCHAR(128),
PasswordSalt NVARCHAR(128)
)

INSERT @Logon
(UserName , HashedPassword , ActualPassword , PasswordSalt)
VALUES
('Fred', HASHBYTES('SHA1', 'Foo' + 'Salty'), N'foo', N'Salty')
,('Alice', HASHBYTES('SHA1', '12345Nhus_uhnk_' + N'123_Salt_My_Churro'), N'12345Nhus_uhnk_', '123_Salt_My_Churro')

SELECT *
FROM @Logon


SELECT *
FROM @Logon
WHERE UserName = 'Alice'
AND HashedPassword = HASHBYTES('SHA1', N'12345Nhus_uhnk_' + PasswordSalt)
It's possible that there is an issue with a unicode conversion. If you take off the "N" in front of the string literals in my sample it will cause issues.
Go to Top of Page

tvb2727
Starting Member

35 Posts

Posted - 2011-08-04 : 14:33:11
My I don't have a password has. Just a pw(the hashed password with the salt) and pws (the password salt). They are both nvarchar(128). I thought if I had something set as a Binary, then someone could figure out it and reverse it?

The password was - password and the password salt was - test
Go to Top of Page

tvb2727
Starting Member

35 Posts

Posted - 2011-08-04 : 14:36:44
Also, what does the N do again? Do I need to include that at the start of the hash? or just to help it out I guess you could say in the code?
Go to Top of Page

tvb2727
Starting Member

35 Posts

Posted - 2011-08-04 : 14:48:26
Also is there a HASH function that is not Bytes and can put in a nvarchar like I was doing?
Go to Top of Page

tvb2727
Starting Member

35 Posts

Posted - 2011-08-04 : 15:06:11
I don't have a password hash in my table. Just a pw(the hashed password with the salt) and pws (the password salt). They are both nvarchar(128). I thought if I had something set as a Binary, then someone could figure out it and reverse it?

The password was - password and the password salt was - test
Go to Top of Page

robvolk
Most Valuable Yak

15732 Posts

Posted - 2011-08-04 : 15:08:39
What are the collations for the password and salt columns? You may have to coerce the variables to be the same if the column collations don't match the database default.
Go to Top of Page

Lamprey
Master Smack Fu Yak Hacker

4614 Posts

Posted - 2011-08-04 : 15:34:02
quote:
Originally posted by tvb2727

Also, what does the N do again? Do I need to include that at the start of the hash? or just to help it out I guess you could say in the code?

It lets SQL know that the string is unicode or double-byte. Which will change your results:
SELECT HASHBYTES('SHA1', 'StringValue')
SELECT HASHBYTES('SHA1', N'StringValue')
Go to Top of Page

Lamprey
Master Smack Fu Yak Hacker

4614 Posts

Posted - 2011-08-04 : 15:36:12
Also, you can extend my example to show that the same logic works, even if you convert the hash to an NVARCHAR(128):
DECLARE @Logon TABLE 
(
UserName NVARCHAR(50),
HashedPassword NVARCHAR(128),
ActualPassword NVARCHAR(128),
PasswordSalt NVARCHAR(128)
)

INSERT @Logon
(UserName , HashedPassword , ActualPassword , PasswordSalt)
VALUES
('Fred', CAST(HASHBYTES('SHA1', 'Foo' + 'Salty') AS NVARCHAR(128)), N'foo', N'Salty')
,('Alice', CAST(HASHBYTES('SHA1', '12345Nhus_uhnk_' + N'123_Salt_My_Churro') AS NVARCHAR(128)), N'12345Nhus_uhnk_', '123_Salt_My_Churro')

SELECT *
FROM @Logon


SELECT *
FROM @Logon
WHERE UserName = 'Alice'
AND HashedPassword = CAST(HASHBYTES('SHA1', N'12345Nhus_uhnk_' + PasswordSalt) AS NVARCHAR(128))
Go to Top of Page

tvb2727
Starting Member

35 Posts

Posted - 2011-08-04 : 15:57:03
Lamprey - I think what you just posted might be what I need. I need more time to put the info in a new store procedure and connect it to my asp.net 4.0 page.

I am still a little confused on the N. I don't need to Pass a 'N' via my website to make this work do I?
Go to Top of Page

robvolk
Most Valuable Yak

15732 Posts

Posted - 2011-08-04 : 16:47:10
The N prefix means to convert the string to an nvarchar literal. If your parameters are declared nvarchar you don't need it.
Go to Top of Page

tvb2727
Starting Member

35 Posts

Posted - 2011-08-04 : 21:08:16
So would this work then with the N in the correct place? (I am not able to test it out right now). Not sure if I am writing the N correctly?



Create PROCEDURE [dbo].[verify_un_and_pw_quick]
@UN VARCHAR(50) = NULL,
@PW NVARCHAR(128) = NULL

AS

BEGIN


SELECT COUNT(*)
FROM [tbl_login]
WHERE (user_name_27 = @UN) AND (pw = = CAST(HASHBYTES('SHA1', N@PW + pws) AS NVARCHAR(128))
END


Go to Top of Page

robvolk
Most Valuable Yak

15732 Posts

Posted - 2011-08-04 : 21:50:42
No, you only need N for a string literal:

N'this is a unicode string'

For the expression you posted, you need to change @UN to nvarchar. Concatenating varchar and nvarchar will implicitly convert the result to nvarchar, but this may affect how HASHBYTES works on it. Better to start with nvarchar on all variables, or explicitly CAST/CONVERT varchar to nvarchar.
Go to Top of Page

tvb2727
Starting Member

35 Posts

Posted - 2011-08-05 : 04:47:57
I have it working and verifying if I run the store procedure in sql server 2008. I can't get it to work with my code in Asp.net 4.0/VB.net code. When I pass my username and password and it returns 0.

Vb.net Code:


Private Shared Function CreatePasswordHash_ONLY(pwd As String) As String
Dim hashedPwd As String = FormsAuthentication.HashPasswordForStoringInConfigFile(pwd, "sha1")

Return hashedPwd
End Function
Protected Sub btnvalidatepw_Click(sender As Object, e As System.EventArgs)
Try
If txtUN.Text = "" Or txtPW.Text = "" Then
MsgBox("Invalid data")
Exit Sub
End If



Using cmd As New SqlCommand("verify_un_and_pw_HASH", mainconnection)
cmd.CommandType = CommandType.StoredProcedure
'specify that the sqlcommand will use a storedprocedure
Dim param As New SqlParameter()
param.ParameterName = "@UN"
'this name needs to match your parameter name you used in the stored proc
param.SqlDbType = SqlDbType.NVarChar
param.Size = 25
param.Direction = ParameterDirection.Input
param.Value = txtUN.Text.Trim
'can be textbox.text or w/e
cmd.Parameters.Add(param)



param = New SqlParameter()
param.ParameterName = "@PW"
'this name needs to match your parameter name you used in the stored proc
param.SqlDbType = SqlDbType.NVarChar
param.Size = 128
param.Direction = ParameterDirection.Input
param.Value = CreatePasswordHash_ONLY(txtPW.Text.Trim)
'can be textbox.text or w/e
cmd.Parameters.Add(param)





'fill the dataset
' adapter.Fill(ds)
mainconnection.Open()
Dim iResults As Integer = cmd.ExecuteScalar()
mainconnection.Close()

If iResults = 1 Then
'The user was found in the DB
MsgBox("The user was found in the DB", MsgBoxStyle.Information, "password 2 step way")
Else
'The user was not found in the DB
MsgBox("The user was not found in the DB", MsgBoxStyle.Exclamation, "password 2 step way")
End If
End Using



Catch ex As Exception
MsgBox(ex.ToString)
End Try
End Sub




Stored Procedure:


USE [timer_it_27]
GO
/****** Object: StoredProcedure [dbo].[verify_un_and_pw_HASH] Script Date: 08/05/2011 03:38:59 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
ALTER PROCEDURE [dbo].[verify_un_and_pw_HASH]
@UN NVARCHAR(50) = NULL,
@PW NVARCHAR(128) = NULL
AS
BEGIN
SELECT COUNT(*)
FROM tbl_login_hash
WHERE UserName = @UN
AND HashedPassword = CAST(HASHBYTES('SHA1', @PW + PasswordSalt) AS NVARCHAR(128))
END

Go to Top of Page

tvb2727
Starting Member

35 Posts

Posted - 2011-08-05 : 05:40:47
Here is my create table:



USE [timer_it_27]
GO

/****** Object: Table [dbo].[tbl_login_hash] Script Date: 08/05/2011 04:39:51 ******/
SET ANSI_NULLS ON
GO

SET QUOTED_IDENTIFIER ON
GO

CREATE TABLE [dbo].[tbl_login_hash](
[UserName] [nvarchar](50) NOT NULL,
[HashedPassword] [nvarchar](128) NULL,
[PasswordSalt] [nvarchar](128) NULL,
[last_login_27] [datetime] NOT NULL,
PRIMARY KEY CLUSTERED
(
[UserName] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY]

GO


Go to Top of Page
    Next Page

- Advertisement -