PeculiarVentures / xadesjs

A pure Typescript/Javascript implementation of XAdES based on XMLDSIGjs. (Keywords: WebCrypto, XMLDSIG, XADES, eIDAS, Trust List, X.509, CRL, OCSP)
https://xadesjs.com
MIT License
141 stars 49 forks source link

I got an error Cannot read property 'hash' of undefined #103

Closed Arsira-star closed 4 years ago

Arsira-star commented 4 years ago

this is my code

const moment = require("moment"); const config = require('../../../config').config; const axios = require('axios'); var SignedXml = require('xml-crypto').SignedXml

// var pkcs11js = require("pkcs11js"); // var pkcs11 = new pkcs11js.PKCS11(); // pkcs11.load("/usr/safenet/lunaclient/lib/libCryptoki2_64.so");

exports.getHashFile = async (req, res, next) => { var getResult = await gethash()

    var xadesjs = require("xadesjs");
    const { Crypto } = require("node-webcrypto-p11");
    const configLuna = {
        library: "/usr/safenet/lunaclient/lib/libCryptoki2_64.so",
        name: "libCryptoki2_64",
        slot: 0,
        readWrite: true,
        pin: "xxxxx"
    };

    const crypto = new Crypto(configLuna);    
    xadesjs.Application.setEngine("NodeJS", crypto);
    var xmlString = '<player bats="left" id="10012" throws="right">\n\t<!-- Here\'s a comment -->\n\t<name>Alfonso Soriano</name>\n\t<position>2B</position>\n\t<team>New York Yankees</team>\n</player>';
    var signedXml;
    var xmlDoc = xadesjs.Parse(xmlString);
    signedXml = new xadesjs.SignedXml();
    signedXml.Sign(              
        { name: "ECDSA", hash: { name: "SHA-1" } },                          
        getResult.key1,                      
        xmlDoc,                               
        {                                       
            keyValue: getResult.key2,
            references: [
                { hash: "SHA-256", transforms: ["enveloped"] }
            ],
            productionPlace: {
                country: "Country",
                state: "State",
                city: "City",
                code: "Code",
            },
            signingCertificate:getResult.sig.toString('hex') }).then(signature => console.log(signature.toString()))

    if(getResult.verify){
        res.status(200).send({data:getResult.sig.toString('hex')})
    }else{
        res.status(200).send('Error')
    }

};

function gethash(){ const graphene = require('graphene-pk11') const mod = graphene.Module.load('/usr/safenet/lunaclient/lib/libCryptoki2_64.so', 'libCryptoki2_64') mod.initialize()

try{        
    const session = mod.getSlots(0).open()
    session.login('xxxx')
    const fetchedCertificates = session.find({label: 'CerBDMS'})
    var fetchedPrivateKey = session.find({label: 'PriBDMS'})
    var fetchedPublicKey = session.find({label: 'PubBDMS'})

    const certificate = fetchedCertificates.items(0).toType()
    var privateKey = fetchedPrivateKey.items(0).toType()
    var publicKey = fetchedPublicKey.items(0).toType()
    const certificateValue = certificate.value

    var sign = session.createSign("SHA256_RSA_PKCS", privateKey);
    sign.update(certificateValue);
    var signature = sign.final();
    //console.log("Signature SHA256_RSA_PKCS :", signature);

    var verify = session.createVerify("SHA256_RSA_PKCS", publicKey);
    verify.update(certificateValue);
    var verify_result = verify.final(signature);
    //console.log("Signature SHA256_RSA_PKCS verify:", verify_result);

    var item = {
        data:certificate,
        key1:privateKey,
        key2:publicKey,
        verify:verify_result,
        sig:signature
    }

    session.logout();
    session.close();
    return item
}
catch(e){
    console.error(e);
}
finally {
    mod.finalize()
}

}

What do I miss ? I use private key and public key from HSM

Arsira-star commented 4 years ago

I try to do another way. If I understand correct. I need to import private key like this const key = await crypto.subtle.importKey("pkcs8", keyDer, alg, false, ["sign"]); to change my private key to cryto type that use to sign in xml but I got this error ' if I use my private key It work fine if I use example key that I got from web site this is private key example "MIIEvAIBADANBgkqhkiG9w0BAQEFAASCBKYwggSiAgEAAoIBAQC4GnIWd1Mxts1ZDCt6JPTV0mvFn+ZrwqE/4WFNAaqtRaChaP21NQ1H55NFNYo1Dl2AhDDNK1MUk+rq6LZOWm8XiuMBA/fs3uBNEloa9WYoAEb3ozS14AG+d1yq41diNl4F2ys1f10s4gW/H27UHl2G1Bgb9Zx1yFZHYItjGKpTl5I8fO/MQtWFvqoK9rY0UxYHpS6Tnfc7ArrQMNsOFu4015N8JuDDtizNxsq8sOK2MgQZNeuOg+ST+8jrJR8CbxRuvejfhZM2QMfBeACjFyxQGBn4UZkys46Y5lXJCx7n6Zix1p+y9qNrJjEdup9O9q9VIjS86K1wPz62JqaVl6R7AgMBAAECggEANdZd+J3q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7B5+rvzyg7ahyighsPGumiXFckwtsc5IqgzNfoKP211+SJONyxzTzR6deYa59mpsyg0fOUqsmR2OgmK5WLZXANDJLYNyTN5hHHflD6yUjG1hHIJvoRJj1caR87lZ9kuV45/WQ=="

And here is modulus from my private key that I got from my HSM "7vi+Wz4kMR0yfBFAm17Yc4mbe2sg2gaJXGMYUt3EPtRdux+crVJ+2RWmaRwaVti5qc+RVzAu/qD+OhQSfMigyZdRwPwub14Xctp17FjIq1DhpHpB+9O9ecUTIrmjXbsq0IsXAsW2BbAMlyMeB3duWdJhaCXL2VXJQkkz88kRGlx0WoSJ4HpW0DWHZFLPLosiRV6iLIIcqA0QSVjuaxV6q9JpkWi2kGJIFr/1KV1xDL+545pCc11oVCVtRGf4Cq9zKxngvGRlZxfnssiHArcbGDwFca8uMws3mmg4KuGtvD5jkLMatpzq8X1MgDG0y0LoZSyJ13bxQ3APss13DXKPCw==" I got this key with 'getAttribute()' from 'graphene-pk11'

first private key has ArrayBuffer { byteLength: 1216 } second has ArrayBuffer { byteLength: 256 }

and here is my hash and alg

const hash = "SHA-256" const alg = { name: "RSASSA-PKCS1-v1_5", hash, } If I use "pkcs8" will get error "Too big integer" If I use another "pkcs" will get the same error that is "'keyData: Is not JSON"

What I need to do next ?

rmhrisk commented 4 years ago

I'm confused. You say you're using an HSM but your importing the key here? If you're using an HSM why are you not using node-webcrypto-p11?

Arsira-star commented 4 years ago

Sorry, It my misunderstanding. Now I know what HSM working. I see node-webcrypto-p11.It work like graphene-pk11 Now I seek the lib that put certificate in xml and generate xml format for digitalsignature Is node-webcrypto-p11 is the answer ?

rmhrisk commented 4 years ago

This library creates XAdES signatures.

node-webcrypto-p11 provides a crypto interface for HSMs that is compatible with webcrypto so you can use HSMs with this library.

Arsira-star commented 4 years ago

Thank for your help I did it