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

Decrypt an S/MIME email and verify its signature

See more Email Object Examples

Register the recipient’s certificate and private key (from a PEM file) before opening signed-encrypted.eml. This workflow expects both encryption and a signature, so it checks both layers before reading the message. Cryptographic signature validity is one input to a signer-trust decision.

Chilkat PHP Downloads

PHP
<?php

use Chilkat2\Cert;
use Chilkat2\Email;
use Chilkat2\Pem;

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

$email = new Email();
// The recipient's certificate and private key are in a PEM file.  The 2nd argument of LoadPemFile
// is the password of the private key.
$pem = new Pem();
try {
    $pem->LoadPemFile('recipient.pem', 'RECIPIENT_PASSWORD');

    $email->AddPemSource($pem);

    $email->LoadEml('signed-encrypted.eml');
} catch (\Chilkat2\Exception $e) {
    echo $e->getMessage(), "\n";
    exit;
}

if ((!$email->ReceivedEncrypted) || (!$email->Decrypted)) {
    echo "Expected a successfully decrypted S/MIME envelope.\n";
    exit;
}

if ((!$email->ReceivedSigned) || (!$email->SignaturesValid)) {
    echo "Expected a valid signature inside the envelope.\n";
    exit;
}

// This message has one signer. Examine its certificate after verification.
$signer = new Cert();
try {
    $email->LastSignerCert(0, $signer);
} catch (\Chilkat2\Exception $e) {
    echo $e->getMessage(), "\n";
    exit;
}

echo 'Signer certificate: ', $signer->SubjectDN, "\n";
echo 'Recovered subject: ', $email->Subject, "\n";
echo 'Recovered attachments: ', $email->NumAttachments, "\n";