Load and add the private key to the PrivateKeyStore:
useSelective\XmlDSig\PrivateKeyStore;
// ...$privateKeyStore = newPrivateKeyStore();
// load a private key from a string$privateKeyStore->loadFromPem('private key content', 'password');
// or load a private key from a PEM file$privateKeyStore->loadFromPem(file_get_contents('filename.pem'), 'password');
// load pfx PKCS#12 certificate from a string$privateKeyStore->loadFromPkcs12('pfx content', 'password');
// or load PKCS#12 certificate from a file$privateKeyStore->loadFromPkcs12(file_get_contents('filename.p12'), 'password');
Define the digest method: sha1, sha224, sha256, sha384, sha512
useSelective\XmlDSig\XmlSigner;
// Create a XmlSigner and pass the crypto signer$xmlSigner = newXmlSigner($cryptoSigner);
// Optional: Set reference URI$xmlSigner->setReferenceUri('');
// Create a signed XML string$signedXml = $xmlSigner->signXml('<?xml ...');
// or sign an XML file$signedXml = $xmlSigner->signXml(file_get_contents($filename));
// or sign an DOMDocument$xml = newDOMDocument();
$xml->preserveWhiteSpace = true;
$xml->formatOutput = false;
$xml->loadXML($data);
$signedXml = $xmlSigner->signDocument($xml);
Note, you can sign an XML signature using ECDSA.
It's not supported to use ECDSA for the digest.
You can find a fully working example in the XmlEcdsaTest test class.
Verify the Digital Signatures of XML Documents
Load the public key(s):
useSelective\XmlDSig\PublicKeyStore;
useSelective\XmlDSig\CryptoVerifier;
useSelective\XmlDSig\XmlSignatureVerifier;
$publicKeyStore = newPublicKeyStore();
// load a public key from a string$publicKeyStore->loadFromPem('public key content');
// or load a public key file$publicKeyStore->loadFromPem(file_get_contents('cacert.pem'));
// or load a public key from a PKCS#12 certificate string$publicKeyStore->loadFromPkcs12('public key content', 'password');
// or load a public key from a PKCS#12 certificate file$publicKeyStore->loadFromPkcs12(file_get_contents('filename.pfx'), 'password');
// Load public keys from DOMDocument X509Certificate nodes$publicKeyStore->loadFromDocument($xml);
// Load public key from existing OpenSSLCertificate resource$publicKeyStore->loadFromCertificate($certificate);
useSelective\XmlDSig\XmlSignatureVerifier;
// Create a verifier instance and pass the crypto decoder$xmlSignatureVerifier = newXmlSignatureVerifier($cryptoVerifier);
// Verify XML from a string$isValid = $xmlSignatureVerifier->verifyXml($signedXml);
// or verify a XML file$isValid = $xmlSignatureVerifier->verifyXml(file_get_contents('signed.xml'));
// or verifying an DOMDocument instance$xml = newDOMDocument();
$xml->preserveWhiteSpace = true;
$xml->formatOutput = false;
$xml->loadXML($data);
$isValid = $xmlSignatureVerifier->verifyDocument($xml);
if ($isValid === true) {
echo'The XML signature is valid.';
} else {
echo'The XML signature is not valid.';
Online XML Digital Signature Verifier
Try these excellent online tools to verify XML signatures: