Sample code for 30+ languages & platforms
B4X Requires Chilkat v11.8.0+

Add a PEM Source for Decrypting Email

See more Email Object Examples

Demonstrates the Chilkat Email.AddPemSource method, which adds the certificates and private keys of a Pem object to the internal list of certificate and private-key sources used during decryption. This example loads a PEM file into a Pem object, adds it as a source, then loads an encrypted email so Chilkat can decrypt it automatically. AddPemSource may be called one or more times, and can be called before receiving the email from an IMAP or POP3 server as well as before loading an encrypted email from a .eml file.

Background: To read an encrypted (S/MIME) email you need the recipient's private key. On Windows, Chilkat automatically searches the system certificate stores, and on macOS the Keychain — so if the key is already installed, no extra step is needed. When the certificate and private key live in a standalone file instead (common on Linux or in server deployments), AddPemSource gives them to Chilkat. A PEM file is a text file that can hold a certificate, the certificates of its chain, and the private key, each between -----BEGIN ...----- and -----END ...----- lines. The private key can be encrypted with a password. AddPemSource was added in Chilkat v11.8.0 and replaces UseCertVault and the AddPfxSource methods.

Chilkat B4X Downloads

B4X
Dim success As Boolean = False

'  Demonstrates the AddPemSource method, which adds the certificates and private keys of a
'  Pem object to the internal list of certificate and private-key sources used during
'  decryption.

Dim email As ChilkatEmail
email.Initialize

'  Load a PEM file containing the certificate and the private key needed to decrypt the message.
'  The 2nd argument of LoadPemFile is the password of the private key.  (Pass an empty string if
'  the private key is not encrypted.)
Dim pem As ChilkatPem
pem.Initialize
success = pem.LoadPemFile("qa_data/certs/decryption.pem", "pem_password")
If success = False Then
    Log(pem.LastErrorText)
    Return
End If


'  AddPemSource may be called one or more times (each call adds more certificates), and should
'  be called before the encrypted email is obtained -- that is, before receiving it from an
'  IMAP or POP3 server, or (as shown here) before loading it from a .eml file -- so Chilkat can
'  decrypt it automatically.
success = email.AddPemSource(pem)
If success = False Then
    Log(email.LastErrorText)
    Return
End If


'  Load an encrypted email; Chilkat uses the PEM source to decrypt it.
success = email.LoadEml("qa_data/eml/encrypted.eml")
If success = False Then
    Log(email.LastErrorText)
    Return
End If


Log("ReceivedEncrypted = " & email.ReceivedEncrypted)
Log("Decrypted = " & email.Decrypted)

'  Note: Paths such as "qa_data/..." are relative local filesystem paths,
'  relative to the current working directory of the running application.