我遇到了有关数字签名和xadesjs
的问题。我在Node.js中编写一个小型服务器,它应该使用XAdES加密XML文件。我有一个PFX文件,我导出为PEM和PK8格式。一般问题是,当我使用xadesjs
生成keyPair时,一切正常。这是一个例子:
// Generate RSA key pair
let privateKey, publicKey;
XAdES.Application.crypto.subtle.generateKey(
{
name: "RSASSA-PKCS1-v1_5",
modulusLength: 1024, //can be 1024, 2048, or 4096,
publicExponent: new Uint8Array([1, 0, 1]),
hash: { name: "SHA-256" }, //can be "SHA-1", "SHA-256", "SHA-384", or "SHA-512"
},
false, //whether the key is extractable (i.e. can be used in exportKey)
["sign", "verify"] //can be any combination of "sign" and "verify"
)
.then(function (keyPair) {
privateKey = keyPair.privateKey;
// Call sign function
return SignXml(xmlString, privateKey,
{ name: "RSASSA-PKCS1-v1_5", hash: { name: "SHA-256" } });
})
.then(function (signedDocument) {
console.log("Signed document:\n\n", signedDocument);
next(null, signedDocument);
})
.catch(function (e) {
console.log(e);
next(e, null);
});
但我一直在使用所有可能的组合来使importKey
方法起作用。例如,即使密钥位于PKCS8(使用OpenSSL导出)中,这也不起作用:
let key = fs.readFileSync("key.pem");
XAdES.Application.crypto.subtle.importKey("pkcs8", key,
{
name: "RSASSA-PKCS1-v1_5",
modulusLength: 2048, //can be 1024, 2048, or 4096,
publicExponent: new Uint8Array([1, 0, 1]),
hash: { name: "SHA-256" },
},
false,
["sign"]
)
.then(function (privateKey) {
// Call sign function
return SignXml(xmlString, privateKey,
{ name: "RSASSA-PKCS1-v1_5", hash: { name: "SHA-256" } });
})
我收到错误:
Error: ImportKey: Can not import key for pkcs8
我的主要目标是获得一个程序,在那里我可以指定数字签名的路径,我的程序将导入密钥和证书,最后用它们签署我的文件。如果所有内容都可以存储在PFX文件中会很舒服,但是如果您有任何解决方案,即使密钥和证书是单独存储的(PEM和PK8),我将不胜感激。
答案 0 :(得分:1)
如果有人有同样的问题。这是@pedrofb的回答帮助实现的。
首先,我在pem
npm包的帮助下获得密钥和证书。然后我删除页眉和页脚并将密钥转换为ArrayBuffer:
const pfx = fs.readFileSync("cert.pfx");
pem.readPkcs12(pfx, { p12Password: "test123" }, (err: any, cert: any) => {
if(err) return console.log(err);
let privateKey = b64ToBinary(removePFXComments(cert.key));
let certificate = removePFXComments(cert.cert);
这里是上面两种使用方法的实现:
function removePFXComments(pem) {
let lines = pem.split('\n');
let encoded = '';
for (let i = 0; i < lines.length; i++) {
if (lines[i].trim().length > 0 &&
lines[i].indexOf('-----BEGIN CERTIFICATE-----') < 0 &&
lines[i].indexOf('-----END CERTIFICATE') < 0 &&
lines[i].indexOf('-----BEGIN RSA PRIVATE KEY-----') < 0 &&
lines[i].indexOf('-----BEGIN RSA PUBLIC KEY-----') < 0 &&
lines[i].indexOf('-----BEGIN PUBLIC KEY-----') < 0 &&
lines[i].indexOf('-----END PUBLIC KEY-----') < 0 &&
lines[i].indexOf('-----BEGIN PRIVATE KEY-----') < 0 &&
lines[i].indexOf('-----END PRIVATE KEY-----') < 0 &&
lines[i].indexOf('-----END RSA PRIVATE KEY-----') < 0 &&
lines[i].indexOf('-----END RSA PUBLIC KEY-----') < 0) {
encoded += lines[i].trim();
}
}
return encoded;
}
function b64ToBinary(base64) {
let raw = atob(base64);
let rawLength = raw.length;
let array = new Uint8Array(new ArrayBuffer(rawLength));
for(let i = 0; i < rawLength; i++) {
array[i] = raw.charCodeAt(i);
}
return array;
}