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

Sign and encrypt an email with S/MIME

See more Email Object Examples

Use the sender’s signing PFX and the recipient’s public RSA certificate with with-attachments.eml, which has one recipient. Supply your own signing-key password from a credential store. Render to bytes to apply both S/MIME operations without connecting to SMTP.

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();
    success = email.LoadEml("with-attachments.eml");
    if (success != true) {
        System.out.println(email.lastErrorText());
        return;
        }

    CkCert signer = new CkCert();
    success = signer.LoadPfxFile("signer.pfx","SIGNER_PASSWORD");
    if (success != true) {
        System.out.println(signer.lastErrorText());
        return;
        }

    CkCert recipient = new CkCert();
    success = recipient.LoadFromFile("recipient.cer");
    if (success != true) {
        System.out.println(recipient.lastErrorText());
        return;
        }

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

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

    email.put_SigningHashAlg("sha256");
    email.put_Pkcs7CryptAlg("aes");
    email.put_Pkcs7KeyLength(256);
    email.put_OaepPadding(true);
    email.put_OaepHash("sha256");
    email.put_OaepMgfHash("sha256");
    email.put_SendSigned(true);
    email.put_SendEncrypted(true);
    CkMailMan mail = new CkMailMan();
    CkBinData rendered = new CkBinData();
    success = mail.RenderToMimeBd(email,rendered);
    if (success != true) {
        System.out.println(mail.lastErrorText());
        return;
        }

    success = rendered.WriteFile("signed-encrypted.eml");
    if (success != true) {
        System.out.println("Failed: rendered.WriteFile.");
        return;
        }

    System.out.println("Saved signed-encrypted.eml.");
  }
}