Sample code for 30+ languages & platforms
SQL Server

Encrypt / Decrypt a File and Verify it has not Changed

See more Encryption Examples

Demonstrates how to encrypt and decrypt a file, and verify it has not changed.

Chilkat SQL Server Downloads

SQL Server
-- 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

    -- This requires the Chilkat API to have been previously unlocked.
    -- See Global Unlock Sample for sample code.

    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, 'CryptAlgorithm', 'aes'
    EXEC sp_OASetProperty @crypt, 'CipherMode', 'cbc'
    EXEC sp_OASetProperty @crypt, 'KeyLength', 128
    EXEC sp_OASetProperty @crypt, 'PaddingScheme', 0

    DECLARE @ivHex nvarchar(4000)
    SELECT @ivHex = '000102030405060708090A0B0C0D0E0F'
    EXEC sp_OAMethod @crypt, 'SetEncodedIV', NULL, @ivHex, 'hex'

    DECLARE @keyHex nvarchar(4000)
    SELECT @keyHex = '00010203040506071011121314151617'
    EXEC sp_OAMethod @crypt, 'SetEncodedKey', NULL, @keyHex, 'hex'

    DECLARE @dataFile nvarchar(4000)
    SELECT @dataFile = 'qa_data/zips/HBIQ040615300005.ZIP'
    DECLARE @outFile nvarchar(4000)
    SELECT @outFile = 'qa_output/HBIQ040615300005.enc'
    DECLARE @outFile2 nvarchar(4000)
    SELECT @outFile2 = 'qa_output/HBIQ040615300005.ZIP'

    EXEC sp_OAMethod @crypt, 'CkEncryptFile', @success OUT, @dataFile, @outFile
    EXEC sp_OAMethod @crypt, 'CkDecryptFile', @success OUT, @outFile, @outFile2

    DECLARE @fac int
    EXEC @hr = sp_OACreate 'Chilkat.FileAccess', @fac OUT

    DECLARE @bEqual int
    EXEC sp_OAMethod @fac, 'FileContentsEqual', @bEqual OUT, @dataFile, @outFile2
    IF @bEqual <> 1
      BEGIN

        PRINT 'Decrypted file not equal to the original.'
      END
    ELSE
      BEGIN

        PRINT 'Success.'
      END

    EXEC @hr = sp_OADestroy @crypt
    EXEC @hr = sp_OADestroy @fac


END
GO