Sample code for 30+ languages & platforms
SQL Server

Add a Recipient Certificate for S/MIME Encryption

See more MIME Examples

Demonstrates AddEncryptCert, which adds one recipient certificate to the list used by EncryptN. Call it once for each intended recipient, then call EncryptN to encrypt for all of them.

The file paths are relative to the application's current working directory. Absolute paths may also be used. Supply the paths appropriate to your own environment.

Background. AddEncryptCert builds up the recipient list used by EncryptN. Only the public key of each certificate is required for encryption.

Chilkat SQL Server Downloads

SQL Server
--
CREATE PROCEDURE ChilkatSample
AS
BEGIN
    DECLARE @hr int
    DECLARE @sTmp0 nvarchar(4000)
    DECLARE @success int
    SELECT @success = 0

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

    EXEC sp_OAMethod @mime, 'SetBodyFromPlainText', @success OUT, 'This message will be encrypted.'
    IF @success = 0
      BEGIN
        EXEC sp_OAGetProperty @mime, 'LastErrorText', @sTmp0 OUT
        PRINT @sTmp0
        EXEC @hr = sp_OADestroy @mime
        RETURN
      END

    --  AddEncryptCert adds one recipient certificate to the list used by EncryptN.  Call it once per
    --  recipient.
    DECLARE @cert int
    EXEC @hr = sp_OACreate 'Chilkat.Cert', @cert OUT

    EXEC sp_OAMethod @cert, 'LoadFromFile', @success OUT, 'qa_data/recipient.cer'
    IF @success = 0
      BEGIN
        EXEC sp_OAGetProperty @cert, 'LastErrorText', @sTmp0 OUT
        PRINT @sTmp0
        EXEC @hr = sp_OADestroy @mime
        EXEC @hr = sp_OADestroy @cert
        RETURN
      END

    EXEC sp_OAMethod @mime, 'AddEncryptCert', @success OUT, @cert
    IF @success = 0
      BEGIN
        EXEC sp_OAGetProperty @mime, 'LastErrorText', @sTmp0 OUT
        PRINT @sTmp0
        EXEC @hr = sp_OADestroy @mime
        EXEC @hr = sp_OADestroy @cert
        RETURN
      END

    --  EncryptN then encrypts for all certificates added.
    EXEC sp_OAMethod @mime, 'EncryptN', @success OUT
    IF @success = 0
      BEGIN
        EXEC sp_OAGetProperty @mime, 'LastErrorText', @sTmp0 OUT
        PRINT @sTmp0
        EXEC @hr = sp_OADestroy @mime
        EXEC @hr = sp_OADestroy @cert
        RETURN
      END

    PRINT 'Encrypted for the added recipient(s).'

    EXEC @hr = sp_OADestroy @mime
    EXEC @hr = sp_OADestroy @cert


END
GO