Sample code for 30+ languages & platforms
PureBasic

PKCS7 Encrypt MIME

See more MIME Examples

Encrypt MIME using a digital certificate to create PKCS7 encrypted S/MIME.

Chilkat PureBasic Downloads

PureBasic
IncludeFile "CkCert.pb"
IncludeFile "CkMime.pb"

Procedure ChilkatExample()

    success.i = 0

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

    mime.i = CkMime::ckCreate()
    If mime.i = 0
        Debug "Failed to create object."
        ProcedureReturn
    EndIf

    ; Build a simple MIME message to be encrypted:
    success = CkMime::ckAddHeaderField(mime,"Content-Type","text/plain")
    success = CkMime::ckAddHeaderField(mime,"abc","123")
    CkMime::ckSetBody(mime,"This is a test")

    ; A digital certificate is required to create PKCS7 encrypted MIME.
    ; It can come from a variety of sources: .cer file, .pfx file, PEM files,
    ; an in-memory representation, or directly from a Windows
    ; registry-based certificate store.

    ; This example will load a certificate object from a .cer file.
    ; Note: Only the public-key is required to encrypt.  (Decryption
    ; requires a private key.)

    cert.i = CkCert::ckCreate()
    If cert.i = 0
        Debug "Failed to create object."
        ProcedureReturn
    EndIf

    success = CkCert::ckLoadFromFile(cert,"myCert.cer")
    If success = 0
        Debug CkCert::ckLastErrorText(cert)
        CkMime::ckDispose(mime)
        CkCert::ckDispose(cert)
        ProcedureReturn
    EndIf

    ; Encrypt the MIME:
    success = CkMime::ckEncrypt(mime,cert)
    If success = 0
        Debug CkMime::ckLastErrorText(mime)
        CkMime::ckDispose(mime)
        CkCert::ckDispose(cert)
        ProcedureReturn
    EndIf

    ; Display the MIME:
    Debug CkMime::ckGetMime(mime)

    ; The resulting S/MIME looks something like this:

    ; abc: 123
    ; Content-Disposition: attachment; filename="smime.p7m"
    ; Content-Transfer-Encoding: base64
    ; Content-Type: application/x-pkcs7-mime;
    ;  name="smime.p7m"
    ; 
    ; MIICAQYJKoZIhvcNAQcDoIIB8jCCAe4CAQAxggGFMIIBgQIBADBpMFUxCzAJBgNVBAYTAlpBMSUw
    ; IwYDVQQKExxUaGF3dGUgQ29uc3VsdGluZyAoUHR5KSBMdGQuMR8wHQYDVQQDExZUaGF3dGUgQ29k
    ; ZSBTaWduaW5nIENBAhB4ouTcAmLszrGi170k1deSMA0GCSqGSIb3DQEBAQUABIIBABz59iwVufLZ
    ; QIPs0whUYMtBjIQxg5IOCxpoKJeJmLVzu9Q5Q1poxG9uYOveybS9c4wbl5A0DFfKTW5O4HhHcOHW
    ; TgcH4iqdwhiFWm/q9d5rjceJWBFQsGOcgoXSU/U2Xp+N47/+Pqyc5XJbxKnOc4YhPzO320JZsNB6
    ; p1NGk5SNnWqgbUDmEnfH8ZPHSV7dNi2aiFALYTyLjyp0lqJCsdZ524OPTZFfusrl/9ibPAW7jKuI
    ; FgDCcBtRJvolVF8iIHxaTw4rhk0qb1KWzxvB5j9HSLdyIKIPhZbxeS10bx18YkSsBlKfdKRalQag
    ; 3oWSRdsK9/N75YHG8Pm+x9BOHUAwYAYJKoZIhvcNAQcBMBkGCCqGSIb3DQMCMA0CAToECAb+toBW
    ; txZigDhGZKSpUpuTiWvvSMemX/c79sSnMpuefVwGKFTDgXVLE2SoD5a9Yh5vcG7Mhl2IkilVwOMc
    ; fi23+g==


    CkMime::ckDispose(mime)
    CkCert::ckDispose(cert)


    ProcedureReturn
EndProcedure