我在使用 xml-crypto 库签署 xml 时遇到问题。 这是我的代码:
const fs = require("fs");
const xmlCrypto = require("xml-crypto");
const xpath = require("xpath");
const dom = require("xmldom").DOMParser;
var xml = "<book><title>Harry Potter</title></book>";
var xmlDocument = new dom().parseFromString(xml, "text/xml");
var node = xpath.select("//title", xmlDocument)[0];
console.log(node.localName + ": " + node.firstChild.data);
console.log("Node: " + node.toString());
const privateKey = fs.readFileSync(
"./certifications/universal-pk.pem",
"utf-8"
);
console.log("privateKey", privateKey);
const reference = {
uri: "",
transforms: ["canonicalize", "c14n"],
digestAlgorithm: "http://www.w3.org/2001/04/xmlenc#sha256",
};
const sig = new xmlCrypto.SignedXml();
sig.addReference(reference);
sig.signingKey = privateKey;
sig.computeSignature(node);
控制台日志:
title: Harry Potter
Node: <title>Harry Potter</title>
privateKey -----BEGIN PRIVATE KEY-----
.......
-----END PRIVATE KEY-----
[xmldom error] invalid doc source
@#[line:0,col:undefined]
\api\node_modules\xml-crypto\node_modules\xpath\xpath.js:1278
throw new Error("XPath parse error");
^
Error: XPath parse error
我还尝试了示例代码 https://www.npmjs.com/package/xml-crypto
但是,我也收到了完全相同的错误消息。
问题是您没有将正确的输入传递给
computeSignature
方法。
文档说:
computeSignature(xml, [options]) - 计算给定 xml 的签名,其中:
xml - 包含 xml 文档的字符串
因此,它需要一个 XML 字符串,但是您在此处发送的
node
变量
sig.computeSignature(node);
实际上是一个
xmldom
对象,因此会出现错误。
因此,请发送 XML 字符串:
sig.computeSignature(node.toString());