forge icon indicating copy to clipboard operation
forge copied to clipboard

Successfully created pkcs7 signature but got crypto verification error: "SIG_CRYPTO_FAILURE"

Open EliasShekh opened this issue 4 years ago • 6 comments
trafficstars

Here is my code:

const fs = require('fs');
const forge = require('node-forge');

let certificate = forge.pki.certificateFromPem(fs.readFileSync("XXX.crt")),
    privateKey = forge.pki.privateKeyFromPem(fs.readFileSync("XXX.key")),
    content = fs.readFileSync('content.xml', 'utf8'),
    p7 = forge.pkcs7.createSignedData();

p7.content = forge.util.createBuffer(content);
p7.addCertificate(certificate);

p7.addSigner({
    key: privateKey,
    certificate: certificate,
    digestAlgorithm: forge.pki.oids.sha1,
    issuer: certificate.issuer.attributes,
    serialNumber: certificate.serialNumber,
    authenticatedAttributes: [
        {
            type: forge.pki.oids.contentType,
            value: forge.pki.oids.data
        },
        {
            type: forge.pki.oids.messageDigest
        },
        {
            type: forge.pki.oids.signingTime
        }
    ]
});

p7.sign();

let signature = Buffer.from(forge.asn1.toDer(p7.toAsn1()).getBytes(), 'binary');

fs.writeFileSync("signature.p7s", signature);

Here is the result from https://ec.europa.eu/cefdigital/DSS/webapp-demo/validation: Screenshot 2021-01-15 121321

Please, help me solve this problem. Thanks in advance!!!

EliasShekh avatar Jan 15 '21 06:01 EliasShekh

Hi I am having the same issue. When I remove the authenticatedAttributes the SIG_CRYPTO_FAILURE disappears but then it fails at the Is the signed qualifying property: 'message-digest' or 'SignedProperties' present? step. Were you able to fix the problem?

CakeAuxAnchois avatar Apr 07 '21 19:04 CakeAuxAnchois

This happens because the library doesn't sort by tag/length attributes (as it should), so they end up in the wrong order which leads to invalid signature.

As a workaround, put them in the following order: content type, signing time, message digest.

ovk avatar May 12 '21 12:05 ovk

@ovk, not getting your order here, why 'signing time' before 'message digest' ?

petitout avatar Feb 10 '22 00:02 petitout

Because this manually produces the correct order (content type is the shortest one, time is longer, digest is the longest). See my reply here https://github.com/digitalbazaar/forge/issues/400#issuecomment-839296548

ovk avatar Feb 10 '22 03:02 ovk

thanks @ovk, My question was more how attributes are compared for sorting purpose ? it is only about the size of the attribute ?

petitout avatar Feb 10 '22 04:02 petitout

They need to be sorted by tag and size.

ovk avatar Feb 10 '22 12:02 ovk