digitalbazaar / forge

A native implementation of TLS in Javascript and tools to write crypto-based and network-heavy webapps
https://digitalbazaar.com/
Other
5.02k stars 769 forks source link

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

Open EliasShekhGain opened 3 years ago

EliasShekhGain commented 3 years ago

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!!!

CakeAuxAnchois commented 3 years ago

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?

ovk commented 3 years ago

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.

petitout commented 2 years ago

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

ovk commented 2 years ago

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

petitout commented 2 years ago

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

ovk commented 2 years ago

They need to be sorted by tag and size.