PHP code example of snowiow / x509ds

1. Go to this page and download the library: Download snowiow/x509ds library. Choose the download type require.

2. Extract the ZIP file and open the index.php.

3. Add this code to the index.php.
    
        
<?php
require_once('vendor/autoload.php');

/* Start to develop here. Best regards https://php-download.com/ */

    

snowiow / x509ds example snippets


use X509DS\Signer;

$signer = Signer::fromPrivateKey('path/to/pkey');
$signer->setTags(
    [
        'Body'                 => '#body',
        'Timestamp'            => '#timestamp',
        'BinarySecurityToken'  => '#binarytoken',
    ]
);
$signer->setCanonization(Canonization::C14N_EXCLUSIVE);
$document = $signer->sign(self::XML); //The signed DOMDocument
$document->saveXml(); //The signed XML document as a string

// Either from the path of the private key
$signer = Signer::fromPrivateKey('path/to/pkey');
// or the string content of the private key
$signer = Signer::fromPrivateKey(file_get_contents('path/to/pkey'));
// or an openssl resource
$signer = Signer::fromPrivateKey(openssl_pkey_get_private(file_get_contents('path/to/pkey')));

// Either from the path of the pfx file
$signer = Signer::fromPfx('/path/to/pfx', 'password of pfx');
// or the string content of the pfx file
$signer = Signer::fromPfx(file_get_contents('/path/to/pfx'), 'password of pfx');

// Can be one of
$signer->setCanonization(Canonization::C14N); //Default
$signer->setCanonization(Canonization::C14N_EXCLUSIVE);
$signer->setCanonization(Canonization::C14N_WITH_COMMENTS);
$signer->setCanonization(Canonization::C14N_WITH_COMMENTS_EXCLUSIVE);

// Can be one of
$signer->setDigestMethod(Digest::SHA1); //Default
$signer->setDigestMethod(Digest::SHA256);
$signer->setDigestMethod(Digest::SHA512);
$signer->setDigestMethod(Digest::RIPEMD160);

// Can be one of
$signer->setSignatureMethod(Digest::SHA1); //Default
$signer->setSignatureMethod(Digest::SHA256);
$signer->setSignatureMethod(Digest::SHA512);
$signer->setSignatureMethod(Digest::RIPEMD160);

// Example values (namespace doesn't need to be given)
$signer->setTarget('Header'); //Default
$signer->setTarget('Body');

// Example
$signer->setTag(
    [
        'Body'                 => '#body',
        'Timestamp'            => '#timestamp',
        'BinarySecurityToken'  => '#binarytoken',
    ]
);

// Example
$signer->setSecurityTokenReference('#binarySecurityToken');

$signedDoc = $signer->sign('path/to/xml'); // from a path
$signedDoc = $signer->sign(file_get_contents('path/to/xml')); // from a content string
// or from a DOMDocument
$document = new DOMDocument();
$document->load('path/to/xml');
$signedDoc = $signer->sign($document);

$signer = Signer::fromPfx('/path/to/pfx', 'password of pfx');
$cert = $signer->getCertificate();