PureBasic
PureBasic
Set the Decryption Certificate and Private Key
See more Email Object Examples
Demonstrates the Chilkat Email.SetDecryptCert2 method, which explicitly provides a certificate and its corresponding private key as separate objects for decrypting a received encrypted email. Set them before loading the encrypted message. This example loads a .cer certificate and a PEM private key, sets both, then loads an encrypted email.
Background: Sometimes the certificate and its private key are stored separately — a public
.cer file plus a PEM (or other format) key file — rather than combined in a PFX. SetDecryptCert2 accepts the two objects individually, which is the natural fit for that arrangement. It is the two-object counterpart to SetDecryptCert, which takes a single certificate that already carries its private key.Chilkat PureBasic Downloads
IncludeFile "CkCert.pb"
IncludeFile "CkPrivateKey.pb"
IncludeFile "CkEmail.pb"
Procedure ChilkatExample()
success.i = 0
; Demonstrates the SetDecryptCert2 method, which explicitly provides a certificate and its
; corresponding private key (as separate objects) for decrypting a received encrypted
; email. Set them before loading the encrypted email.
email.i = CkEmail::ckCreate()
If email.i = 0
Debug "Failed to create object."
ProcedureReturn
EndIf
; Load the certificate (public) and the matching private key from separate files.
cert.i = CkCert::ckCreate()
If cert.i = 0
Debug "Failed to create object."
ProcedureReturn
EndIf
success = CkCert::ckLoadFromFile(cert,"qa_data/certs/recipient.cer")
If success = 0
Debug CkCert::ckLastErrorText(cert)
CkEmail::ckDispose(email)
CkCert::ckDispose(cert)
ProcedureReturn
EndIf
privKey.i = CkPrivateKey::ckCreate()
If privKey.i = 0
Debug "Failed to create object."
ProcedureReturn
EndIf
success = CkPrivateKey::ckLoadPemFile(privKey,"qa_data/certs/recipient_privkey.pem")
If success = 0
Debug CkPrivateKey::ckLastErrorText(privKey)
CkEmail::ckDispose(email)
CkCert::ckDispose(cert)
CkPrivateKey::ckDispose(privKey)
ProcedureReturn
EndIf
; Provide the certificate and private key to use for decryption.
success = CkEmail::ckSetDecryptCert2(email,cert,privKey)
If success = 0
Debug CkEmail::ckLastErrorText(email)
CkEmail::ckDispose(email)
CkCert::ckDispose(cert)
CkPrivateKey::ckDispose(privKey)
ProcedureReturn
EndIf
; Load the encrypted email; Chilkat decrypts it using the certificate and key.
success = CkEmail::ckLoadEml(email,"qa_data/eml/encrypted.eml")
If success = 0
Debug CkEmail::ckLastErrorText(email)
CkEmail::ckDispose(email)
CkCert::ckDispose(cert)
CkPrivateKey::ckDispose(privKey)
ProcedureReturn
EndIf
Debug "Decrypted = " + Str(CkEmail::ckDecrypted(email))
; Note: Paths such as "qa_data/..." are relative local filesystem paths,
; relative to the current working directory of the running application.
CkEmail::ckDispose(email)
CkCert::ckDispose(cert)
CkPrivateKey::ckDispose(privKey)
ProcedureReturn
EndProcedure