Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SQL to create .Net Membership Provider users

I have a SQL script that creates users in in my database. It uses the .Net membership stored procs.

At this point it works fine.

The only issue is that the passwords are saved clear text. What should I change here to they are salted/encrypted (Not sure what term to use here)

GO

DECLARE @return_value int,
  @UserId uniqueidentifier


EXEC @return_value = [dbo].[aspnet_Membership_CreateUser]
  @ApplicationName = N'Theater',
  @UserName = N'sam.sosa',
  @Password = N'mypassword',
  @PasswordSalt = N'eyhKDP858wdrYHbBmFoQ6DXzFE1FB+RDP4ULrpoZXt6f',
  @Email = N'[email protected]',
  @PasswordQuestion = N'Whats your favorite color',
  @PasswordAnswer = N'Fusia',
  @IsApproved = 1,
  @CurrentTimeUtc = '2010-03-03',
  @CreateDate = '2010-03-03',
  @UniqueEmail = 1,
  @PasswordFormat = 0,
  @UserId = @UserId OUTPUT

SELECT @UserId as N'@UserId'

SELECT 'Return Value' = @return_value

GO

thanks!

like image 211
aron Avatar asked Jun 26 '10 17:06

aron


1 Answers

Under the hood it looks like for the "Hashed" password storage mode, it simply calculates:

SHA1(Salt + Password)

The Salt is stored Base64 encoded, so it must be decoded prior to being concatenated with the (Unicode) password. Finally, the result is Base64 encoded for storage.

The following (horrible) SQL will output a suitably encoded value which can be substituted in place of the "mypassword" that you currently have. You must also set @PasswordFormat to 1 to indicate that the password is stored hashed.

declare @salt nvarchar(128)
declare @password varbinary(256)
declare @input varbinary(512)
declare @hash varchar(64)

-- Change these values (@salt should be Base64 encoded)
set @salt = N'eyhKDP858wdrYHbBmFoQ6DXzFE1FB+RDP4ULrpoZXt6f'
set @password = convert(varbinary(256),N'mypassword')

set @input = hashbytes('sha1',cast('' as  xml).value('xs:base64Binary(sql:variable(''@salt''))','varbinary(256)') + @password)
set @hash = cast('' as xml).value('xs:base64Binary(xs:hexBinary(sql:variable(''@input'')))','varchar(64)')

-- @hash now contains a suitable password hash
-- Now create the user using the value of @salt as the salt, and the value of @hash as the password (with the @PasswordFormat set to 1)

DECLARE @return_value int, 
  @UserId uniqueidentifier 

EXEC @return_value = [dbo].[aspnet_Membership_CreateUser] 
  @ApplicationName = N'Theater', 
  @UserName = N'sam.sosa', 
  @Password = @hash, 
  @PasswordSalt = @salt, 
  @Email = N'[email protected]', 
  @PasswordQuestion = N'Whats your favorite color', 
  @PasswordAnswer = N'Fusia', 
  @IsApproved = 1, 
  @CurrentTimeUtc = '2010-03-03', 
  @CreateDate = '2010-03-03', 
  @UniqueEmail = 1, 
  @PasswordFormat = 1, 
  @UserId = @UserId OUTPUT 

SELECT @UserId as N'@UserId' 

SELECT 'Return Value' = @return_value 
like image 184
Iridium Avatar answered Oct 08 '22 06:10

Iridium