Skip to content

how to sign XML string correctly #510

Description

@davi-canuto

Is your feature request related to a problem? Please describe...

import fs from 'fs'
import { SignedXml } from 'xml-crypto'

const privateKey = fs.readFileSync('./private-key.pem', 'utf-8')
const certBase64 = fs.readFileSync('./cert.pem', 'utf-8')
  .replace(/-----BEGIN CERTIFICATE-----|-----END CERTIFICATE-----|\r?\n/g, '')

export function signInfNFe(infNFeXml: string): string {
  const id = infNFeXml.match(/Id="([^"]+)"/)?.[1]
  if (!id) throw new Error('Não foi possível extrair o ID do infNFe')

  const signer = new SignedXml()
  signer.signingKey = privateKey
  signer.signatureAlgorithm = 'http://www.w3.org/2000/09/xmldsig#rsa-sha1'
  signer.canonicalizationAlgorithm = 'http://www.w3.org/TR/2001/REC-xml-c14n-20010315'

  signer.keyInfoProvider = {
    getKeyInfo: () => `<X509Data><X509Certificate>${certBase64}</X509Certificate></X509Data>`,
    getKey: () => Buffer.from('')
  } as any

  signer.addReference(
    `//*[@Id='${id}']`,
    [
      'http://www.w3.org/2000/09/xmldsig#enveloped-signature',
      'http://www.w3.org/TR/2001/REC-xml-c14n-20010315'
    ],
    'http://www.w3.org/2000/09/xmldsig#sha1'
  )

  signer.computeSignature(infNFeXml)
  return signer.getSignatureXml()
}
 

i have this code for sign my XML before send it inside my soap envelope, but ever return for me "Signature differs from calculated".

context: i wanna connect with sefaz to create for a homologation NF-e https://www.nfe.fazenda.gov.br/portal/listaConteudo.aspx?tipoConteudo=ndIjl+iEFdE=

any problems visible with my signature?

Describe teh solution you'd like...

i want to sign my xml correctly

Describe the alternatives you've considered...

create another microservice in another language to sign correctly my xml before send to the consumer

"xml-crypto": "^2.1.2",

Activity

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions