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

Verify DKIM using a public key supplied as text

See more DKIM Examples

Applications that keep public keys in configuration can pass a complete PEM string or the base64 value of the DNS p= tag to LoadPublicKey. This example reads a trusted PEM as text so it can be run alongside the file-based example. Supply just the key material when passing a base64 value. Reuse the same verifier for signatures with that exact domain and selector.

Chilkat PHP Downloads

PHP
<?php

use Chilkat2\BinData;
use Chilkat2\Dkim;
use Chilkat2\JsonObject;
use Chilkat2\StringBuilder;

$success = false;

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

$message = new BinData();
try {
    $message->LoadFile('signed.eml');
} catch (\Chilkat2\Exception $e) {
    echo "Could not read signed.eml.\n";
    exit;
}

$verifier = new Dkim();
$domain = 'example.com';
$selector = 'mail2026';
$keyText = new StringBuilder();
try {
    $keyText->LoadFile('dkim-public.pem', 'utf-8');
} catch (\Chilkat2\Exception $e) {
    echo "Could not read the trusted public PEM.\n";
    exit;
}

try {
    $verifier->LoadPublicKey($selector, $domain, $keyText->GetAsString());
} catch (\Chilkat2\Exception $e) {
    echo $e->getMessage(), "\n";
    exit;
}

// signed.eml from the signing example has our newly added signature at index zero.
if ($verifier->NumDkimSigs($message) == 0) {
    echo "No DKIM signature in signed.eml.\n";
    exit;
}

try {
    $verifier->DkimVerify(0, $message);
} catch (\Chilkat2\Exception $e) {
    echo $e->getMessage(), "\n";
    echo $verifier->VerifyInfo, "\n";
    exit;
}

$info = new JsonObject();
try {
    $info->Load($verifier->VerifyInfo);
    $success = true;
} catch (\Chilkat2\Exception $e) {
    $success = false;
}
if ((!$success) || ((!$info->StringOfEquals('domain', $domain, true)) || (!$info->StringOfEquals('selector', $selector, true)))) {
    echo "The first signature is not from the selected domain and selector.\n";
    exit;
}

echo "The configured public key verifies this message.\n";