2
const computehash = (pay) => {
  const hashType = crypto.createHash('sha256');
  gen_hash = hashType.update(pay).digest('hex');
  return gen_hash
}

const  JWS_Header =(kid) =>{
  return {
      alg : 'RS256',
      kid: kid.toLowerCase() // shoulw be in lowercase
  };
}


const  JWS_Claims=(payload,appID)=>{
  const payloadHash = computehash(JSON.stringify(payload));
  return {
      ts:  new Date(new Date().toUTCString()), //  UTC time string
      hsh : payloadHash,
      uid : appID
  }
}

const getPrivateKey = async (DSCertPath,pwd) => {
  const pfx = fs.readFileSync(__dirname+DSCertPath);
  return new Promise(async (resolve, reject) => {
    pem.readPkcs12(pfx, { p12Password: pwd}, (err, cert) => {
      console.log('err::: ', err);
      resolve(cert);
    });
  });
}
// function to create the jws signature
const  createJWS = async (appID,payload,certSN,DSCertPath,pwd)=> {
  try{

  const jws_header = JWS_Header(certSN);
  const jws_claims =  JWS_Claims(payload,appID);
  let encodedHeader = Buffer.from(JSON.stringify(jws_header)).toString('base64').replace('+','-').replace('/','_').replace('=',"");
  let encodedClaims = Buffer.from(JSON.stringify(jws_claims)).toString('base64').replace('+','-').replace('/','_').replace('=',"");
  const jws_header_claim = `${encodedHeader}.${encodedClaims}`;
  //const pem = rsu.readFile(DSCertPath);
  //const decryptedKey = pki.decryptRsaPrivateKey(pem, pwd);
  const {key} = await getPrivateKey(DSCertPath,pwd);
   console.log('--key',key)
  // create sign
  const sign = crypto.createSign('SHA256');
  sign.update(jws_header_claim);
  sign.end();
  
  // sign the jws header claim using the private key
  const signature = sign.sign(key);
  const encodedsign = Buffer.from(signature).toString('base64').split("/").join("_").split("+").join("-").split("=").join("")


  const JWS = `${jws_header_claim}.${encodedsign}`
  return JWS
  }
  catch(err){
    console.log('---err inside jws',err)
    throw err
  }
}

const getP2PEConfig = async (certPath,pwd,appID,payload,certSN,DSCertPath) =>{
  const agent = new https.Agent({
    rejectUnauthorized: false, 
      cert: fs.readFileSync(__dirname+certPath),
      passphrase: pwd
  });
return {
  headers: { 'Keep-Alive':false, 'Content-Type': 'application/json','p2peAppID': appID, 'Accept':'application/json','signature': await createJWS(appID,payload,certSN,DSCertPath,pwd) },
  httpsAgent: agent
};
}

// here there are two certs being used one is for the tls cert that is attached in the https Agent , and other one in create JWS function to create the JWS signature using the private key of the digital signature certificate.

const detokenize = async(certPath, pwd,appID,payload,certSN,DSCertPath) => {
    const url = (env === "prod") ? config.p2peDeTokenizeProdEndpoint : config.p2peDeTokenizeTestEndpoint;
    const reqConfig= getP2PEConfig(certPath,pwd,appID,payload,certSN,DSCertPath)
    return axios.post(url, payload, reqConfig);
}

but everything is computed correctly it get the below error, which is giving something to cert attachment process of the exactly not sure about the error

--error happened-- Error: error:0909006C:PEM routines:get_name:no start line
    at Object.createSecureContext (_tls_common.js:129:17)
    at Object.connect (_tls_wrap.js:1580:48)
    at Agent.createConnection (https.js:129:22)
    at Agent.createSocket (_http_agent.js:323:26)
    at Agent.addRequest (_http_agent.js:274:10)
    at new ClientRequest (_http_client.js:306:16)
    at Object.request (https.js:313:10)
    at RedirectableRequest._performRequest (/Users/v0k0108/Desktop/STFC/NextGen/stfc-pci-node-client/node_modules/follow-redirects/index.js:241:24)
    at new RedirectableRequest (/Users/v0k0108/Desktop/STFC/NextGen/stfc-pci-node-client/node_modules/follow-redirects/index.js:60:8)
    at Object.wrappedProtocol.request (/Users/v0k0108/Desktop/STFC/NextGen/stfc-pci-node-client/node_modules/follow-redirects/index.js:437:14) {
  library: 'PEM routines',
  function: 'get_name',
  reason: 'no start line',
  code: 'ERR_OSSL_PEM_NO_START_LINE'
}
(node:46264) UnhandledPromiseRejectionWarning: Error: error:0909006C:PEM routines:get_name:no start line
    at Object.createSecureContext (_tls_common.js:129:17)
    at Object.connect (_tls_wrap.js:1580:48)
    at Agent.createConnection (https.js:129:22)
    at Agent.createSocket (_http_agent.js:323:26)
    at Agent.addRequest (_http_agent.js:274:10)
    at new ClientRequest (_http_client.js:306:16)
    at Object.request (https.js:313:10)
    at RedirectableRequest._performRequest (/Users/v0k0108/Desktop/STFC/NextGen/stfc-pci-node-client/node_modules/follow-redirects/index.js:241:24)
    at new RedirectableRequest (/Users/v0k0108/Desktop/STFC/NextGen/stfc-pci-node-client/node_modules/follow-redirects/index.js:60:8)
    at Object.wrappedProtocol.request (/Users/v0k0108/Desktop/STFC/NextGen/stfc-pci-node-client/node_modules/follow-redirects/index.js:437:14)
(Use `node --trace-warnings ...` to show where the warning was created)
(node:46264) UnhandledPromiseRejectionWarning: Unhandled promise rejection. This error originated either by throwing inside of an async function without a catch block, or by rejecting a promise which was not handled with .catch(). To terminate the node process on unhandled promise rejection, use the CLI flag `--unhandled-rejections=strict` (see https://nodejs.org/api/cli.html#cli_unhandled_rejections_mode). (rejection id: 3)
(node:46264) [DEP0018] DeprecationWarning: Unhandled promise rejections are deprecated. In the future, promise rejections that are not handled will terminate the Node.js process with a non-zero exit code.

use pem library for reading the private key

marc_s
  • 732,580
  • 175
  • 1,330
  • 1,459
vignesh K B
  • 124
  • 3
  • 10
  • Could the issue be that the certificate _isn't_ in the correct format or it's being read wrong after all? The error itself would suggest the read certificate isn't in the expected format, as in [this other question](https://stackoverflow.com/questions/63030755/error-error0909006cpem-routinesget-nameno-start-line-node). – MJV Jun 14 '22 at 13:31

0 Answers0