phpxmlhashcanonicalization

Canonicalization of an XML document in PHP


I am trying to canonicalize an XML document in PHP.

Here is the XML document:

<?xml version="1.0" encoding="ISO-8859-1"?>
<Envelope xmlns="http://example.org/envelope">
  <Body>
    Olá mundo
  </Body>
</Envelope>

its an example from https://www.di-mgt.com.au/xmldsig2.html#twotypes.

the expected hash value is :

516b984d8ba0d7427593984a7e89f1b6182b011f

What I did in PHP :

<?php
header('Content-Type: text/plain');
$xml = new DOMDocument( "1.0", "utf-8" );
$string = '<Envelope xmlns="http://example.org/envelope">
<Body>
  Olá mundo
</Body>
</Envelope>'; 
$xml->loadXML($string);
$xml = $xml->C14N();
echo hash('sha1', $xml);
?>

however, the hash value is :

0ae2e4b4834d3a31447c50a3905669520be2bc73

Solution

  • Whitesapace it's important when doing C14N. XML sample is missing some of that in both the plain XML and PHP code.
    Adding the missing withespace the sha1sum is correct

    $string = '<Envelope xmlns="http://example.org/envelope">
      <Body>
        Olá mundo
      </Body>
      
    </Envelope>';
    

    Whitespace as shown on the provided URL

    <Envelope xmlns="http://example.org/envelope">¶
    ♦♦<Body>¶
    ♦♦♦♦Olá mundo¶
    ♦♦</Body>¶
    ♦♦¶
    </Envelope>