如何在SQL Server 2008 R2中加密和解密密码?

时间:2016-06-07 23:55:54

标签: sql-server

如何在SQL Server 2008 R2中加密和解密密码?请使用散列字节函数和salt值描述步骤中的所有过程?

2 个答案:

答案 0 :(得分:0)

不要以纯文本或加密方式在数据库中保存密码。甚至没有像MD5或SHA-512这样的哈希值。如果没有盐渍和迭代,这是不够的。

存储密码的盐渍,迭代HMAC。使用Bcrypt,password_hash,PBKDF2等功能。

答案 1 :(得分:-1)

    CREATE TABLE dbo.[User]
    (
        UserID INT IDENTITY(1,1) NOT NULL,
        LoginName NVARCHAR(40) NOT NULL,
        PasswordHash BINARY(64) NOT NULL,
        Salt UNIQUEIDENTIFIER NOT NULL,
        FirstName NVARCHAR(40) NULL,
        LastName NVARCHAR(40) NULL,
        CONSTRAINT [PK_User_UserID] PRIMARY KEY CLUSTERED (UserID ASC)
    )

    CREATE PROCEDURE dbo.uspAddUser
        @pLogin NVARCHAR(50), 
        @pPassword NVARCHAR(50),
        @pFirstName NVARCHAR(40) = NULL, 
        @pLastName NVARCHAR(40) = NULL,
        @responseMessage NVARCHAR(250) OUTPUT
    AS
    BEGIN
        SET NOCOUNT ON

        DECLARE @salt UNIQUEIDENTIFIER=NEWID()
        BEGIN TRY

            INSERT INTO dbo.[User] (LoginName, PasswordHash, Salt, FirstName, LastName)
            VALUES(@pLogin, HASHBYTES('SHA2_512', @pPassword+CAST(@salt AS NVARCHAR(36))), @salt, @pFirstName, @pLastName)

           SET @responseMessage='Success'

        END TRY
        BEGIN CATCH
            SET @responseMessage=ERROR_MESSAGE() 
        END CATCH
    END

CREATE PROCEDURE dbo.uspLogin
    @pLoginName NVARCHAR(254),
    @pPassword NVARCHAR(50),
    @responseMessage NVARCHAR(250)='' OUTPUT
AS
BEGIN

    SET NOCOUNT ON

    DECLARE @userID INT

    IF EXISTS (SELECT TOP 1 UserID FROM [dbo].[User] WHERE LoginName=@pLoginName)
    BEGIN
        SET @userID=(SELECT UserID FROM [dbo].[User] WHERE LoginName=@pLoginName AND PasswordHash=HASHBYTES('SHA2_512', @pPassword+CAST(Salt AS NVARCHAR(36))))

       IF(@userID IS NULL)
           SET @responseMessage='Incorrect password'
       ELSE 
           SET @responseMessage='User successfully logged in'
    END
    ELSE
       SET @responseMessage='Invalid login'

END