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

Extract PKCS7 from MIME and Decrypt

See more MIME Examples

Extracts the base64-encoded PKCS7 body of a MIME message to a file, and then decrypts using Chilkat Crypt2.

Chilkat Java Downloads

Java
import com.chilkatsoft.chilkat2.ChilkatException;
import com.chilkatsoft.chilkat2.Crypt2;
import com.chilkatsoft.chilkat2.Mime;
import com.chilkatsoft.chilkat2.Pem;

public class ChilkatExample {

    public static void main(String[] args) {
        // This example assumes the Chilkat API to have been previously unlocked.
        // See Global Unlock Sample for sample code.

        Mime mime = new Mime();

        try {
            mime.loadMimeFile("c:/aaworkarea/EmailInBytes.txt");

            mime.saveBody("c:/aaworkarea/smime.p7m");
        } catch (ChilkatException e) {
            System.out.println(e.getLastErrorText());
            return;
        }

        Crypt2 crypt = new Crypt2();

        // The certificate and its private key are in a PEM file.  The 2nd argument of LoadPemFile is the
        // password of the private key.  (Pass an empty string if the private key is not encrypted.)
        Pem pem = new Pem();
        try {
            pem.loadPemFile("c:/aaworkarea/my.pem", "pemPassword");

            crypt.addPemSource(pem);
        } catch (ChilkatException e) {
            System.out.println(e.getLastErrorText());
            return;
        }

        // Indicate the public-key (PKCS7) encryption/decryption should be used:
        crypt.setCryptAlgorithm("pki");

        String inPath = "c:/aaworkarea/smime.p7m";
        String outPath = "c:/aaworkarea/decrypted.dat";

        try {
            crypt.ckDecryptFile(inPath, outPath);
        } catch (ChilkatException e) {
            System.out.println(e.getLastErrorText());
            return;
        }

        System.out.println("Success.");
    }
}