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

Decrypt a saved S/MIME message with a PEM file

See more Email Object Examples

Register the recipient certificate and private key before loading encrypted.eml. Check that an encryption layer was present and successfully removed before writing a plaintext copy. Choose a protected output directory appropriate for that copy.

Chilkat CkJava Downloads

CkJava
import com.chilkatsoft.*;

public class ChilkatExample {

  static {
    try {
        System.loadLibrary("chilkat");
    } catch (UnsatisfiedLinkError e) {
      System.err.println("Native code library failed to load.\n" + e);
      System.exit(1);
    }
  }

  public static void main(String argv[])
  {
    boolean success = false;

    //  Assumes Chilkat is unlocked. See Global Unlock Sample.

    CkEmail email = new CkEmail();
    //  The recipient's certificate and private key are in a PEM file.  The 2nd argument of LoadPemFile
    //  is the password of the private key.
    CkPem pem = new CkPem();
    success = pem.LoadPemFile("recipient.pem","PEM_PASSWORD");
    if (success != true) {
        System.out.println(pem.lastErrorText());
        return;
        }

    success = email.AddPemSource(pem);
    if (success != true) {
        System.out.println(email.lastErrorText());
        return;
        }

    success = email.LoadEml("encrypted.eml");
    if (success != true) {
        System.out.println(email.lastErrorText());
        return;
        }

    if (email.get_ReceivedEncrypted() != true) {
        System.out.println("The input has no S/MIME encryption layer.");
        return;
        }

    if (email.get_Decrypted() != true) {
        System.out.println("Could not decrypt with the available private keys.");
        return;
        }

    success = email.SaveEml("decrypted.eml");
    if (success != true) {
        System.out.println(email.lastErrorText());
        return;
        }

    System.out.println("Saved decrypted.eml.");
  }
}