SQL Server
SQL Server
Example: Hash Text in Chunks
Shows how to generate a final hash, like SHA-256, for a large text by processing it in chunks.Chilkat SQL Server Downloads
-- Important: See this note about string length limitations for strings returned by sp_OAMethod calls.
--
CREATE PROCEDURE ChilkatSample
AS
BEGIN
DECLARE @hr int
DECLARE @success int
SELECT @success = 0
DECLARE @crypt int
EXEC @hr = sp_OACreate 'Chilkat.Crypt2', @crypt OUT
IF @hr <> 0
BEGIN
PRINT 'Failed to create ActiveX component'
RETURN
END
EXEC sp_OASetProperty @crypt, 'HashAlgorithm', 'sha256'
EXEC sp_OASetProperty @crypt, 'Charset', 'utf-8'
DECLARE @bd int
EXEC @hr = sp_OACreate 'Chilkat.BinData', @bd OUT
DECLARE @s nvarchar(4000)
SELECT @s = 'The quick brown fox jumped over the lazy dog.' + CHAR(13) + CHAR(10)
-- Accumulate the text in a StringBuilder. We'll demonstrate hashing the text in chunks,
-- and then also hashing the entire text at once to show the results are the same.
EXEC sp_OAMethod @bd, 'AppendString', @success OUT, @s, 'utf-8'
EXEC sp_OAMethod @crypt, 'HashBeginString', @success OUT, @s
DECLARE @i int
SELECT @i = 0
WHILE @i < 200
BEGIN
EXEC sp_OAMethod @bd, 'AppendString', @success OUT, @s, 'utf-8'
EXEC sp_OAMethod @crypt, 'HashMoreString', @success OUT, @s
SELECT @i = @i + 1
END
-- Get the hash in base64 format.
EXEC sp_OASetProperty @crypt, 'EncodingMode', 'base64'
DECLARE @encodedHash nvarchar(4000)
EXEC sp_OAMethod @crypt, 'HashFinalENC', @encodedHash OUT
PRINT 'Hash computed in chunks: ' + @encodedHash
-- Let's alternatively compute the hash of the entire amount of data at once,
-- to show the hash computation is the same:
EXEC sp_OAMethod @crypt, 'HashBdENC', @encodedHash OUT, @bd
PRINT 'Hash computed in 1 step: ' + @encodedHash
-- Output:
-- Hash computed in chunks: unwkVff61k40roRIJizaknreScHaL6frWe37kydXbZQ=
-- Hash computed in 1 step: unwkVff61k40roRIJizaknreScHaL6frWe37kydXbZQ=
EXEC @hr = sp_OADestroy @crypt
EXEC @hr = sp_OADestroy @bd
END
GO