开发者

Stored procedure that (doesn't) returns hashed string

I'm trying to write a Stored Procedure which'll get a str开发者_开发知识库ing, hash it with SHA1 and then return the hash. I can't seem to make it return @hashedString. I'll admit I'm a total beginner with T-SQL.

I'm writing the T-SQL directly in the db.

This is what I've gotten up to now:

ALTER PROCEDURE dbo.ConvertToHash

 (
 @stringToHash nvarchar(256),
 @hashedString nvarchar(256) OUTPUT
 )

AS
 DECLARE @HashThis nvarchar(256);
 SELECT @HashThis = CONVERT(nvarchar(256), @stringToHash);
 SELECT @hashedString = HashBytes('SHA1', @HashThis);


HashBytes returns a VARBINARY result, ie. a byte array. I strongly suggest you keep this type, don't convert it to a string. If you have to convert it, use Base64 encoding.

Right now your procedure casts the hash to an Unicode string, but this is incorrect because not all byte combinations are valid in Unicode and the hash may well hit on invalid Unicode characters.

ALTER PROCEDURE dbo.ConvertToHash
 (
 @stringToHash nvarchar(256),
 @hashedString binary(20) OUTPUT
 )
AS
 SET @hashedString = HashBytes('SHA1', @stringToHash);

Make sure you preserve the hashed value as BINARY(20) everywhere in your code, and use it as byte[] in your client. Never convert the hash to a string (this applies to every language and platform out there).


Your final select statement is assigning the value rather than returning it. You can either issue another select statement on the relevant variable (modified code included below for your reference) or you can incorporate OUTPUT parameters into your Stored Procedure design, as suggested by Remus.

ALTER PROCEDURE dbo.ConvertToHash

 (
 @stringToHash nvarchar(256),
 @hashedString nvarchar(256) OUTPUT
 )

AS
 DECLARE @HashThis nvarchar(256);
 SELECT @HashThis = CONVERT(nvarchar(256), @stringToHash);
 SELECT @hashedString = HashBytes('SHA1', @HashThis);
 SELECT @hashedString 
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜