PHP code example of lenincrdva / xades-bes-signer

1. Go to this page and download the library: Download lenincrdva/xades-bes-signer 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/ */

    

lenincrdva / xades-bes-signer example snippets




adesBesSigner\Certificate\P12CertificateLoader;
use XadesBesSigner\Signature\SignatureContext;
use XadesBesSigner\Signer;

$key = P12CertificateLoader::fromFile('token.p12', 'clave-de-token');

// SHA-1 por defecto (compatible con el SRI).
// Para SHA-256: new SignatureContext(DigestCalculator::SHA256);
$context = new SignatureContext();

$signer = new Signer($key);
$signedXml = $signer->signFromFile('factura.xml', $context);

file_put_contents('factura-firmada.xml', $signedXml);



adesBesSigner\Verification\Verifier;

$result = (new Verifier())->verifyFromFile('factura-firmada.xml');

if ($result->isValid()) {
    echo 'Firma válida: ' . $result->getSignerCommonName() . PHP_EOL;
    echo 'Fecha: ' . $result->getSigningTime()?->format('c') . PHP_EOL;
} else {
    foreach ($result->getErrors() as $error) {
        echo "- {$error}" . PHP_EOL;
    }
}

use XadesBesSigner\Xml\DigestCalculator;

$key = P12CertificateLoader::fromFile('token.p12', 'clave', DigestCalculator::SHA256);
$context = new SignatureContext(DigestCalculator::SHA256);

use XadesBesSigner\BatchSigner;
use XadesBesSigner\Certificate\P12CertificateLoader;

$key = P12CertificateLoader::fromFile('token.p12', 'clave');
$batch = BatchSigner::with($key);

// Firma todos los *.xml del directorio; cada archivo se escribe como
// <nombre>-signed.xml en la carpeta de salida.
$results = $batch->signDirectory('facturas/', 'facturas/firmadas/');

use XadesBesSigner\Certificate\Certificate;
use XadesBesSigner\KeyProvider\PrivateKeySignerInterface;

final class HsmSigner implements PrivateKeySignerInterface
{
    public function sign(string $data): string
    {
        // Delega en tu HSM/API: `$data` es el SignedInfo canónico (bytes).
    }

    public function getCertificate(): Certificate
    {
        // Certificado del token, p. ej. Certificate::fromPem(...).
    }
}
yaml
services:
  php:
    build: .
    volumes:
      - ./docker/openssl.cnf:/etc/ssl/openssl.cnf:ro
bash
export OPENSSL_CONF=/ruta/a/docker/openssl.cnf
php -S localhost:8000
bash
php -r 'var_dump(openssl_get_provider_configs());'
bash
php -r 'BesSigner\Certificate\P12CertificateLoader::fromFile("token.p12", "clave");
echo $s->getCertificate()->getCommonName(), PHP_EOL;'