The document I am signing looks like this.
<?xml version="1.0" encoding="UTF-8"?>
<?xml-stylesheet href="CDA_PL_IG_1.3.1.xsl" type="text/xsl"?>
<ClinicalDocument></ClinicalDocument>
I am using xadesjs
to sign this XML with the following code:
const crypto = new Crypto();
xadesjs.Application.setEngine('NodeJS', crypto);
export async function sign(xml: string, { publicKey, privateKey }: any) {
const hash = 'SHA-1';
const alg = {
name: 'RSASSA-PKCS1-v1_5',
hash
};
const keyDer = pem2der(privateKey.toString());
const key = await crypto.subtle.importKey('pkcs8', keyDer, alg, true, [ 'sign' ]);
const parsed = xadesjs.Parse(xml.trim());
const xadesXml = new xadesjs.SignedXml();
const signature = await xadesXml.Sign(alg, key, parsed, {
signingCertificate: preparePem(publicKey.toString()),
references: [ { uri: '', hash, transforms: [ 'enveloped' ] } ],
x509: [ preparePem(publicKey.toString()) ]
});
parsed.documentElement.appendChild(signature.GetXml()!);
return parsed.toString();
}
function preparePem(pem: string) {
return pem.replace(/-----(BEGIN|END)[\w\d\s]+-----/g, '').replace(/[\r\n]/g, '');
}
function pem2der(pem: string) {
pem = preparePem(pem);
return new Uint8Array(Buffer.from(pem, 'base64')).buffer;
}
The generated signature is valid only if I remove the xml declaration and stylesheet instruction. So only signing this returns a correctly signed document:
<ClinicalDocument></ClinicalDocument>
Signing this
<?xml version="1.0" encoding="UTF-8"?>
<?xml-stylesheet href="CDA_PL_IG_1.3.1.xsl" type="text/xsl"?>
<ClinicalDocument></ClinicalDocument>
errors with message saying that not the entire document is signed.
I assume the problem is with the URI=""
reference. It signs only the <ClinicalDocument>
and leaves the <?xml version>
and <?xml-stylesheet>
with no signature.
How do I sign everything?