From 89609544792ad809ee53cdaf8a449b75aa3de6a4 Mon Sep 17 00:00:00 2001 From: shunkica Date: Mon, 29 May 2023 15:59:48 +0200 Subject: [PATCH] Add support for appending attributes to KeyInfo element (#285) --- index.d.ts | 1 + lib/signed-xml.js | 8 +++++++- test/signature-unit-tests.js | 30 ++++++++++++++++++++++++++++++ 3 files changed, 38 insertions(+), 1 deletion(-) diff --git a/index.d.ts b/index.d.ts index 89e242fb..c54595c3 100644 --- a/index.d.ts +++ b/index.d.ts @@ -81,6 +81,7 @@ export class SignedXml { export interface KeyInfo { getKey(keyInfo?: Node[] | null): Buffer; getKeyInfo(key?: string, prefix?: string): string; + attrs?: {[key: string]: any} | undefined; } export class FileKeyInfo implements KeyInfo { diff --git a/lib/signed-xml.js b/lib/signed-xml.js index 77bb0d5d..ea4d792d 100644 --- a/lib/signed-xml.js +++ b/lib/signed-xml.js @@ -846,7 +846,13 @@ SignedXml.prototype.getKeyInfo = function(prefix) { currentPrefix = currentPrefix ? currentPrefix + ':' : currentPrefix if (this.keyInfoProvider) { - res += "<" + currentPrefix + "KeyInfo>" + var keyInfoAttrs = "" + if (this.keyInfoProvider.attrs) { + Object.keys(this.keyInfoProvider.attrs).forEach((name) => { + keyInfoAttrs += " " + name + "=\"" + this.keyInfoProvider.attrs[name] + "\"" + }) + } + res += "<" + currentPrefix + "KeyInfo" + keyInfoAttrs + ">" res += this.keyInfoProvider.getKeyInfo(this.signingCert || this.signingKey, prefix) res += "" } diff --git a/test/signature-unit-tests.js b/test/signature-unit-tests.js index 4467f9e0..eff239e8 100644 --- a/test/signature-unit-tests.js +++ b/test/signature-unit-tests.js @@ -734,6 +734,36 @@ module.exports = { test.done(); }, + "adds attributes to KeyInfo element when attrs are present in keyInfoProvider": function (test) { + var xml = ""; + var sig = new SignedXml(); + sig.signingKey = fs.readFileSync("./test/static/client.pem"); + sig.keyInfoProvider = { + attrs: { + CustomUri: "http://www.example.com/keyinfo", + CustomAttribute: "custom-value" + }, + getKeyInfo: function () { + return ""; + } + }; + + sig.computeSignature(xml); + var signedXml = sig.getSignedXml(); + + var doc = new dom().parseFromString(signedXml); + var keyInfoElement = select("//*[local-name(.)='KeyInfo']", doc.documentElement); + test.equal(keyInfoElement.length, 1, "KeyInfo element should exist"); + + var algorithmAttribute = keyInfoElement[0].getAttribute('CustomUri'); + test.equal(algorithmAttribute, 'http://www.example.com/keyinfo', "KeyInfo element should have the correct CustomUri attribute value"); + + var customAttribute = keyInfoElement[0].getAttribute('CustomAttribute'); + test.equal(customAttribute, 'custom-value', "KeyInfo element should have the correct CustomAttribute attribute value"); + + test.done(); + }, + } function passValidSignature(test, file, mode) {