错误:0909006C:PEM例程:GET_NAME:无启动行,同时使用带有JWS签名的SSL CERT进行Axios Post请求

发布于 2025-02-03 06:53:50 字数 5517 浏览 2 评论 0原文

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
};
}

//这里有两个证书用于HTTPS代理中附加的TLS证书,另一个用于创建JWS函数中的另一个证书,以使用数字签名证书的私钥创建JWS签名。

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);
}

但是所有内容都是正确计算的,它会遇到以下错误,这给确切的附件提供了一些问题,不确定有关错误的错误

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

使用PEM库来读取私钥

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

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。
列表为空,暂无数据
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文