Sample code for 30+ languages & platforms
SQL Server

Decrypt a Password-Encrypted Email with AES

See more Email Object Examples

Demonstrates the Chilkat Email.AesDecrypt method, which decrypts and restores an email message previously encrypted with AesEncrypt. The password must be the same one used to encrypt. This is Chilkat's password-based email-object decryption — it is not S/MIME certificate-based decryption. This example encrypts an email and then decrypts it to recover the original body.

Background: Symmetric encryption is reversible with the same secret: the identical password that scrambled the message unscrambles it. There is no separate "public" and "private" key as in S/MIME — which makes the scheme simple but means anyone holding the password can both encrypt and decrypt. The round trip shown here (encrypt then decrypt) is a common way to verify the password and confirm the content is faithfully restored.

Chilkat SQL Server Downloads

SQL Server
--
CREATE PROCEDURE ChilkatSample
AS
BEGIN
    DECLARE @hr int
    DECLARE @sTmp0 nvarchar(4000)
    --  Demonstrates the AesDecrypt method, which decrypts and restores an email that was
    --  previously encrypted with AesEncrypt.  The password must match the one used to encrypt.
    --  This example encrypts an email, then decrypts it to restore the original content.

    DECLARE @email int
    EXEC @hr = sp_OACreate 'Chilkat.Email', @email OUT
    IF @hr <> 0
    BEGIN
        PRINT 'Failed to create ActiveX component'
        RETURN
    END

    EXEC sp_OASetProperty @email, 'Subject', 'Confidential'
    EXEC sp_OASetProperty @email, 'Body', 'Secret contents.'

    --  Encrypt with a password...
    DECLARE @success int
    EXEC sp_OAMethod @email, 'AesEncrypt', @success OUT, 'secret_password'

    --  ...then decrypt with the same password to restore the original email.
    EXEC sp_OAMethod @email, 'AesDecrypt', @success OUT, 'secret_password'


    EXEC sp_OAGetProperty @email, 'Body', @sTmp0 OUT
    PRINT 'Body after decrypt = ' + @sTmp0

    EXEC @hr = sp_OADestroy @email


END
GO