Import private key from .p12 file to sign an XML file with XAdES-BES Signature
jhcueva opened this issue · 0 comments
jhcueva commented
Hello everyone I'm using xadesjs specifically the XAdES-BES Signature, to sign a document that will be validated by the entity to manage the payment of Ecuadorian taxpayers. I've been following the steps of the documentation.
First I have lo load the private key in order to use the function SignXml(xmlString, keys, algorithm). For that I have implemented the following code:
const fs = require("fs");
var { Crypto } = require("@peculiar/webcrypto");
const xadesjs = require("xadesjs");
const { XMLSerializer } = require("xmldom");
const crypto = new Crypto();
xadesjs.Application.setEngine("NodeJS", new Crypto());
// Hash and algorith from the example
const hash = "SHA-1";
const alg = {
name: "RSASSA-PKCS1-v1_5",
hash,
};
function preparePem(pem) {
return (
pem
// remove BEGIN/END
.replace(/-----(BEGIN|END)[\w\d\s]+-----/g, "")
// remove \r, \n
.replace(/[\r\n]/g, "")
);
}
function pem2der(pem) {
pem = preparePem(pem);
// convert base64 to ArrayBuffer
return new Uint8Array(Buffer.from(pem, "base64")).buffer;
}
// Set the path of the .p12 file
const path = require("path");
const p12Path = path.resolve(__dirname, "cert.p12");
//Read key
const keyPem = fs.readFileSync(p12Path, { encoding: "utf-8" });
const keyDer = pem2der(keyPem);
//Retrieve the key to sign the document
const key = xadesjs.Application.crypto.subtle.importKey(
"pkcs8",
keyDer,
alg,
false,
["sign"]
);
But I have the following error:
throw new Error(asn1Parsed.result.error);
^
Error: End of input reached before message was fully decoded (inconsistent offset and length values)
at Function.parse (/home/baeto/Documents/xades/node_modules/@peculiar/asn1-schema/build/cjs/parser.js:14:19)
at Function.importKey (/home/baeto/Documents/xades/node_modules/@peculiar/webcrypto/build/webcrypto.js:863:54)
at RsaSsaProvider.onImportKey (/home/baeto/Documents/xades/node_modules/@peculiar/webcrypto/build/webcrypto.js:1036:37)
at RsaSsaProvider.importKey (/home/baeto/Documents/xades/node_modules/webcrypto-core/build/webcrypto-core.js:234:33)
at SubtleCrypto.importKey (/home/baeto/Documents/xades/node_modules/webcrypto-core/build/webcrypto-core.js:1475:29)
at Object.<anonymous> (/home/baeto/Documents/xades/index.js:42:47)
at Module._compile (node:internal/modules/cjs/loader:1105:14)
at Object.Module._extensions..js (node:internal/modules/cjs/loader:1159:10)
at Module.load (node:internal/modules/cjs/loader:981:32)
at Function.Module._load (node:internal/modules/cjs/loader:822:12)
Any suggestions are welcome!