Nueva pregunta

Pregunta:

Fecha: 20-04-2023 23:01:18 (En Español)

alguien sabe como realizar el firmado de documentos XML con PHP nativo, con certificado .p12?[No resuelta]

Cuento con el Siguiente codigo genera la firma para el documento xml pero al la firma es invalidad ya que al parecer se modifico el documento xml por lo que se invalida la firma.
// Cargar el documento XML a firmar
$documento = new DOMDocument();
$documento->load('documento.xml');
// Leer el archivo .p12 y extraer la clave privada y el certificado
$p12 = file_get_contents('certificado.p12');
$password = 'contraseña_certificado'; // Contraseña del archivo .p12
if (openssl_pkcs12_read($p12, $certs, $password)) {
$private_key = $certs['pkey'];
$certificate = $certs['cert'];
} else {
die('Error al leer el archivo .p12');
}

// Generar el valor del DigestValue
$digestValue = base64_encode(hash('sha256', $documento->C14N(true), true));

//$DigestValue=base64_encode(hash('sha256', $documento->C14N(true), true));
// Crear el objeto OpenSSL para la firma digital
openssl_sign($documento->C14N(), $signature, $private_key, OPENSSL_ALGO_SHA256);

// Crear el elemento XML de la firma digital
$firma = $documento->createElementNS('http://www.w3.org/2000/09/xmldsig#', 'Signature');
$documento->documentElement->appendChild($firma);

// Crear los elementos XML de la firma digital
$info = $documento->createElement('SignedInfo');
$firma->appendChild($info);

$canon = $documento->createElement('CanonicalizationMethod');
$info->appendChild($canon);
$canon->setAttribute('Algorithm', 'http://www.w3.org/TR/2001/REC-xml-c14n-20010315');

$sign = $documento->createElement('SignatureMethod');
$info->appendChild($sign);
$sign->setAttribute('Algorithm', 'http://www.w3.org/2001/04/xmldsig-more#rsa-sha256');

$ref = $documento->createElement('Reference');
$info->appendChild($ref);
$ref->setAttribute('URI', '');

$transforms = $documento->createElement('Transforms');
$ref->appendChild($transforms);

$tran = $documento->createElement('Transform');
$transforms->appendChild($tran);
$tran->setAttribute('Algorithm', 'http://www.w3.org/2000/09/xmldsig#enveloped-signature');

$digest = $documento->createElement('DigestMethod');
$ref->appendChild($digest);
$digest->setAttribute('Algorithm', 'http://www.w3.org/2001/04/xmlenc#sha256');
$signatureValue = $documento->createElement('SignatureValue', base64_encode($signature));
$firma->appendChild($signatureValue);

$keyInfo = $documento->createElement('KeyInfo');
$firma->appendChild($keyInfo);

$X509Data = $documento->createElement('X509Data');
$keyInfo->appendChild($X509Data);

$X509Cert = $documento->createElement('X509Certificate', base64_encode($certificate));
$X509Data->appendChild($X509Cert);

$digestValue = $documento->createElement('DigestValue', base64_encode(hash('sha256', $documento->C14N(true), true)));
$ref->appendChild($digestValue);

// Guardar el documento XML firmado
$documento->save('documento_firmado.xml');
Etiquetas: Firma Digital - PHP Votos: 0 - Respuestas: 6 - Vistas: 8 Compartir en: Google Facebook Twitter LinkedIn Link
 

Respuestas:

  • Fecha: 23-05-2023 06:08:55 Haaaa ya entendi donde esta el error.. lo hice corre tu codigo en mi computadora y corregi varios errores.. te lo paso corregido.. Suerte..!!! Que la fuerza te acompañe

    // Cargar el documento XML a firmar
    $documento = new DOMDocument();
    $documento->load('documento.xml');

    // Leer el archivo .p12 y extraer la clave privada y el certificado
    $p12 = file_get_contents('certificado.p12');
    $password = 'contraseña_certificado'; // Contraseña del archivo .p12

    if (openssl_pkcs12_read($p12, $certs, $password)) {
    $private_key = $certs['pkey'];
    $certificate = $certs['cert'];
    } else {
    die('Error al leer el archivo .p12');
    }

    // Crear el objeto OpenSSL para la firma digital
    $private_key_resource = openssl_pkey_get_private($private_key);

    // Generar el valor del DigestValue
    $digestValue = base64_encode(hash('sha256', $documento->C14N(true), true));

    // Crear el elemento XML de la firma digital
    $firma = $documento->createElementNS('http://www.w3.org/2000/09/xmldsig#', 'Signature');
    $documento->documentElement->appendChild($firma);

    // Crear los elementos XML de la firma digital
    $info = $documento->createElement('SignedInfo');
    $firma->appendChild($info);

    $canon = $documento->createElement('CanonicalizationMethod');
    $info->appendChild($canon);
    $canon->setAttribute('Algorithm', 'http://www.w3.org/TR/2001/REC-xml-c14n-20010315');

    $sign = $documento->createElement('SignatureMethod');
    $info->appendChild($sign);
    $sign->setAttribute('Algorithm', 'http://www.w3.org/2001/04/xmldsig-more#rsa-sha256');

    $ref = $documento->createElement('Reference');
    $info->appendChild($ref);
    $ref->setAttribute('URI', '');

    $transforms = $documento->createElement('Transforms');
    $ref->appendChild($transforms);

    $tran = $documento->createElement('Transform');
    $transforms->appendChild($tran);
    $tran->setAttribute('Algorithm', 'http://www.w3.org/2000/09/xmldsig#enveloped-signature');

    $digest = $documento->createElement('DigestMethod');
    $ref->appendChild($digest);
    $digest->setAttribute('Algorithm', 'http://www.w3.org/2001/04/xmlenc#sha256');

    $digestValueElement = $documento->createElement('DigestValue', $digestValue);
    $ref->appendChild($digestValueElement);

    // Firmar el documento XML
    openssl_sign($documento->C14N(), $signature, $private_key_resource, OPENSSL_ALGO_SHA256);
    $signatureValue = $documento->createElement('SignatureValue', base64_encode($signature));
    $firma->appendChild($signatureValue);

    $keyInfo = $documento->createElement('KeyInfo');
    $firma->appendChild($keyInfo);

    $X509Data = $documento->createElement('X509Data');
    $keyInfo->appendChild($X509Data);

    $X509Cert = $documento->createElement('X509Certificate', base64_encode($certificate));
    $X509Data->appendChild($X509Cert);

    // Guardar el documento XML firmado
    $documento->save('documento_firmado.xml');
      Votos: 0 - Link respuesta
     
  • Fecha: 23-05-2023 07:49:44 Buenas Estimado, muchas gracias pero el código aun sigue generando el mismo problema, la firma es invalida ya que se a modificado algo en el proceso y no logro encontrar ese algo.   Votos: 0 - Link respuesta
     
  • Fecha: 23-05-2023 16:35:20 muestrame el error que te sale.. haci te podre ayudar   Votos: 0 - Link respuesta
     
  • Fecha: 23-05-2023 17:06:58 https://drive.google.com/file/d/1IMIyPd4P4R_HmiQBRfi_NMjnfSPjOpej/view?usp=sharing
    hay te paso la captura de la validación de la firma el código genera la firma pero la entidad certificadora lo observa.
      Votos: 0 - Link respuesta
     
  • Fecha: 23-05-2023 17:10:29 Si puede échame una mano con el código por favor, estoy en la disponibilidad de reconocer su colaboración por favor comunícate con migo al Cel. & whatsapp +591 71002661   Votos: 0 - Link respuesta
     
  • Fecha: 01-08-2023 23:48:57 Hola:

    Si estás usando un webservice SOAP probablemente te convenga usar las librerías propias de PHP.

    Aquí te dejo un ejemplo que puede orientarte.

    Saludos,
      Votos: 0 - Link respuesta
     
Para participar activamente de la comunidad primero debes autenticarte, ingresa al sistema.Iniciar Sesión
 
frjcbbae garagebible.com