我在使用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"],
    digest算法rithm: "http://www.w3.org/2001/04/xmlenc#sha256",
  };

  const sig = new xmlCrypto.SignedXml();
  sig.addReference(reference);
  sig.signingKey = privateKey;
  sig.computeSignature(node);

和控制台日志(log):

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

我还try 了 https://www.npmjs.com/package/xml-crypto

但是,我也收到了同样的错误信息.

推荐答案

问题是您没有将正确的输入传递给computeSignature方法.

doctor 说:

CulteSignature(XML,[Options])-计算给定XML的签名,其中:

XML-包含XML文档的字符串

https://www.npmjs.com/package/xml-crypto#signing-xml-documents

因此,它接受一个XML字符串,但这里发送的是node个变量

sig.computeSignature(node);

实际上是一个xmldom的对象,因此产生了错误.

因此,改为发送一个XML字符串:

sig.computeSignature(node.toString());

此外,您似乎正在使用某个较旧的版本,因此根据当前文档进行更改时,您的代码应该如下所示:

(请注意,您并不真的需要使用DOMParser,您可以在引用中传递XML字符串和修改XPath Select 器)

var sig = new xmlCrypto.SignedXml({ privateKey });
sig.addReference({
  xpath: "//*[local-name(.)='title']",
  digest算法rithm: "http://www.w3.org/2000/09/xmldsig#sha1",
  transforms: ["http://www.w3.org/2001/10/xml-exc-c14n#"],
});
sig.canonicalization算法rithm = "http://www.w3.org/2001/10/xml-exc-c14n#";
sig.signature算法rithm = "http://www.w3.org/2000/09/xmldsig#rsa-sha1";
sig.computeSignature(node.toString()); // or just xml and modify xpath..

Node.js相关问答推荐

链接Inbox类方法,范围在哪里以及为什么发生变化?

在Node.js下使用PostgreSQL客户端聚合PostgreSQL中的用户定义类型

编辑Mongoose中的对象嵌套数组

如何在Mongoose中调用动态Collection ?

使用 Google Drive API 按文件夹 ID 检索文件夹的内容

我收到警告:发现函数rs-ms-v1不受支持的运行时nodejs18.x× 不受支持的运行时

Express Web 服务器部署到 prod 但 GET 返回超时错误

Mongodb - 在数组数组中查找()

GitLab 依赖扫描需要源代码中的 package-lock.json 才能执行

为什么我的 Node.js 应用程序在登录时无法正确验证密码(使用 Passport-local 和 bcryptjs)?

如何让 vscode 假设一个 node.js 上下文,以便它不假设 `fetch` 存在?

[NodeJs 从 ADAL 升级到 MSAL]:无法在字符串上创建属性authenticationScheme

在数组的另一个对象中获取数组的mongoose 对象

无法通过谷歌Electron 表格 api( node js)中的服务帐户访问写入

NodeJs 过滤掉目录异步

解决并行保存到 mongodb

mongoose 模式中的嵌套对象

如何在 MongoDB 上只收听 localhost

Npm postinstall 仅用于开发

nodemon + express,监听端口=?