ALTER FUNCTION [dbo].[HMAC]
(
@key VARCHAR(MAX),
@message VARCHAR(MAX)
)
RETURNS VARCHAR(MAX)
AS
BEGIN
--HASH key if longer than 16 characters
IF(LEN(@key) >64)
SET @key = HASHBYTES('md5',@key)
DECLARE @i_key_pad VARCHAR(MAX), @o_key_pad VARCHAR(MAX), @position INT
SET @position = 1
SET @i_key_pad = ''
SET @o_key_pad = ''
--splice ipad & opod with key
WHILE @position <= LEN(@key)
BEGIN
SET @i_key_pad = @i_key_pad + CHAR(ASCII(SUBSTRING(@key, @position, 1)) ^ 54)
SET @o_key_pad = @o_key_pad + CHAR(ASCII(SUBSTRING(@key, @position, 1)) ^ 92)
SET @position = @position + 1
END
--pad i_key_pad & o_key_pad
SET @i_key_pad = LEFT(@i_key_pad + REPLICATE('6',64),64)
SET @o_key_pad = LEFT(@o_key_pad + REPLICATE('\',64),64)
RETURN HASHBYTES('md5',CONVERT(VARBINARY(MAX),@o_key_pad) + HASHBYTES('md5',@i_key_pad + @message))
END
|