How LibreDTE Lib Core signs XML documents for the SII, Chile's tax authority, with three generic packages: Derafu XML for the document, Derafu Certificate for who signs and Derafu Signature for the signature, and what they leave to the library that knows the rules.
Signing XML for Chile’s tax authority: three packages, each with one job
Derafu DEV builds free software libraries. This post is about three of them, derafu/xml, derafu/certificate and derafu/signature, and about the free library that depends on them, LibreDTE Lib Core. Lib Core generates and signs electronic tax documents for the SII, the Servicio de Impuestos Internos, which is Chile’s tax authority.
Where they come from
LibreDTE Lib Core started in 2015 as one repository with everything inside: the handling of XML, the electronic signature, utilities for Chile, the messages, the PDF generation and everything about the SII. It worked, but a person who only needed to sign an XML had to install an invoicing library for Chile. The code for certificates and XML could serve other projects, and it was trapped inside this one.
The rule that came out of it was simple: what does not depend on the SII or on Chile becomes a package of its own. Three pieces of that first repository became packages, with no reference to the SII left in them: the XML, the certificates and the signature. LibreDTE Lib Core declares all three in its composer.json today. LibreDTE tells the whole story of this split in an article, in Spanish.
Three jobs
- Derafu XML is the document. It converts XML to PHP arrays and back, validates it against an XSD schema, queries it with XPath and gives its canonical form (C14N). It also keeps the encoding that the document declares, UTF-8 by default and ISO-8859-1 or others when the XML says so. That matters here: as the article of LibreDTE explains, the SII works with XML in ISO-8859-1, and a signature depends on every byte being right.
- Derafu Certificate is who signs. It loads X.509 and PKCS#12 certificates (the
.p12or.pfxfile) from a file or from data, and it reads the ID, the name, the email, the issuer and the validity. It gives the keys, and a validator checks that the certificate has an ID in the format that you ask for and that it is not expired. All the calls to OpenSSL go through one service, so the errors of one call do not mix with the ones of another. - Derafu Signature is the signature. It signs an XML document with XML-DSIG, the whole document or only one element, and it validates a signed document. It uses the other two: XML for the document and Certificate for the keys.
The certificate
$loader = new CertificateLoader();
$certificate = $loader->loadFromFile('/path/to/certificate.p12', 'password');
$certificate->getId(); // The ID of the owner, for example "12345678-9".
$certificate->getName();
$certificate->getEmail();
$certificate->isActive(); // It is not expired.
$certificate->getExpirationDays();
// Check that it has an ID in the format that you expect. The format is yours: the
// validator does not know what an ID looks like, because that depends on who issues
// the certificates. If it does not match, it throws a CertificateException that
// says the ID and the format.
(new CertificateValidator('/^\d+-[\dK]$/'))->validate($certificate);
Everything that fails in the package is a CertificateException, so one catch takes all of them. Its message carries the explanation of OpenSSL, and the package has its Spanish translation. A wrong password, for example, says:
It was not possible to read the digital certificate data. MAC verification failed in
PKCS12, certificate or password is incorrect (Error #11800071).
The signature
// Sign the whole document, or only the element that has this ID.
$signedXml = $signatureService->signXml($xml, $certificate);
$signedXml = $signatureService->signXml($xml, $certificate, 'elementId');
// Validate it. You get one result for each signature in the document, and you check
// each one. It throws a SignatureException only if the XML is malformed or if it
// has no signature at all.
foreach ($signatureService->validateXml($signedXml) as $signature) {
if (!$signature->isValid()) {
echo $signature->getError()?->getMessage();
}
}
The signature that it writes is an enveloped signature, with canonical XML 1.0, RSA-SHA1 and a SHA1 digest, and the certificate goes inside it:
<Signature xmlns="http://www.w3.org/2000/09/xmldsig#">
<SignedInfo>
<CanonicalizationMethod Algorithm="http://www.w3.org/TR/2001/REC-xml-c14n-20010315"/>
<SignatureMethod Algorithm="http://www.w3.org/2000/09/xmldsig#rsa-sha1"/>
<Reference URI="#elementId">
<!-- The transform, the SHA1 digest method and the digest value. -->
</Reference>
</SignedInfo>
<SignatureValue>...</SignatureValue>
<KeyInfo>
<!-- The public key and the X509 certificate of the signer. -->
</KeyInfo>
</Signature>
The service is built from the XML service, as the documentation shows, or it is wired for you if your application uses Symfony’s container: the package brings its own signature-services.yaml.
Testing without a real certificate
A real certificate is something you do not want in a test. SelfSignedCertificate makes one for testing, with a certificate authority and a user certificate inside a PKCS#12, and you load it as any other:
$selfSigned = new SelfSignedCertificate();
$certificate = $loader->loadFromArray($selfSigned->toArray());
With it, a test can sign a document and validate the result without any real credential.
What they do not do
- They do not know the rules of the SII. Which element has to be signed, which ID it has, in which order the parts go and which schemas apply are rules of the SII, and they live in LibreDTE Lib Core. Signing is not invoicing: these packages sign any XML, in any country.
- The XML signature has one algorithm. It is RSA-SHA1 with a SHA1 digest. If the authority you work with asks for another algorithm in the XML signature, this package does not produce it. XAdES and XML encryption are not included either. Signing plain data, which is a different call, does accept any algorithm that OpenSSL offers.
- There are wider libraries. For more algorithms, XML encryption or the needs of SAML,
robrichards/xmlseclibsis the most widely used library for XML security in PHP, and it is far more used than these packages. - The requirements. PHP 8.5 or later with the
opensslandmbstringextensions, and the Derafu packages are published asdev-mainfor now.
In short
Signing an XML takes three things that are easy to confuse: the document, the identity of who signs and the signature. Keeping each in its own package let LibreDTE Lib Core use them for the SII, and it lets anyone use them for any XML, without installing an invoicing library for Chile. The rules of the SII remain where they belong, in Lib Core.
The reference of Derafu XML, Derafu Certificate and Derafu Signature has every method and every error.