SignXML
Signs an XML document using an enveloped signature following the XMLDSig standard. This is required for invoice validation by the Bolivian tax authority (SIN). The function uses thegoxmldsig library to create a canonicalized (C14N) XML signature with RSA-SHA256 algorithm.
Function Signature
Parameters
The XML document to be signed as a byte array.
File path to the RSA private key in PEM format. Supports both PKCS#1 and PKCS#8 formats.
File path to the X.509 certificate in PEM format.
Returns
The signed XML document with the digital signature embedded.
Error if signing fails (invalid key, certificate, or XML format).
XML Signing Process
The signing process follows these steps:- Load Private Key: Reads the RSA private key from the PEM file, supporting both PKCS#1 and PKCS#8 formats.
- Load Certificate: Reads the X.509 certificate from the PEM file.
- Configure Key Store: Creates a key store with the private key and certificate.
-
Configure Signing Context: Sets up the signing context with:
- C14N 1.0 with comments canonicalization
- RSA-SHA256 signature algorithm
-
Parse XML: Parses the input XML using the
etreelibrary. -
Create Enveloped Signature: Generates an enveloped signature that embeds the
<Signature>element within the XML document. - Serialize: Converts the signed XML back to bytes.
Signature Format
The function creates an enveloped signature, where the<Signature> element is added as a child of the root element:
Example
Private Key Format Support
The function automatically detects and supports two private key formats:PKCS#1 Format
PKCS#8 Format
Certificate Requirements
The X.509 certificate must:- Be in PEM format
- Match the private key
- Be issued by a certificate authority recognized by the tax authority (SIN)
- Be valid (not expired)
- Have the appropriate key usage extensions for digital signatures
Security Considerations
- Private Key Protection: Store private keys securely and restrict file permissions (e.g.,
chmod 600). - Certificate Validation: Ensure certificates are from trusted sources and not expired.
- Key Strength: Use RSA keys of at least 2048 bits.
- Algorithm: The function uses RSA-SHA256, which meets current security standards.
Error Handling
The function returns errors for:- Invalid or missing private key file
- Invalid or missing certificate file
- Malformed PEM format
- Invalid XML structure
- Signature generation failures
- Key type mismatch (non-RSA keys)
Dependencies
This function relies on:github.com/beevik/etree- XML parsing and manipulationgithub.com/russellhaering/goxmldsig- XMLDSig signature generation- Standard Go crypto libraries (
crypto/rsa,crypto/x509)
Related
- CUF Generator - Generate unique invoice codes
