ASSINAR XML NFE

MALA 14/05/2017 13:00:02
#473934
BOM DIA, ESTOU COM PROBLEMA EM ASSINAR XML NFE, ATE SEXTA FUNCIONOU LEGAL, ONTEM COMEÇOU DA ERRO NA ASSINATURA, ALGEM PODE ME PASSAR UM EXEMPLO DE UMA FUNÇÃO QUE ESTEJA FUNCIONANDO, A QUE EU ESTOU USANDO E ESSA FUNÇÃO. ASSINA MAS DA ERRO.


DESDEJA AGREDEÇO A ATENÇÃO DE TODOS.

Public Sub Assinar(ByVal pArqXMLAssinar As String, ByVal pUri As String, ByVal pCertificado As X509Certificate2)
[ô]Abrir o arquivo XML a ser assinado e ler o seu conteúdo
[ô]Exit Sub

Dim SR As StreamReader
Dim vXMLString As String = [Ô][Ô]

System.Net.ServicePointManager.SecurityProtocol = Net.SecurityProtocolType.Ssl3

SR = File.OpenText(pArqXMLAssinar)
vXMLString = SR.ReadToEnd()
SR.Close()

[ô] //Atualizar atributos de retorno com conteúdo padrão
vResultado = 0
vResultadoString = [Ô]Assinatura realizada com sucesso[Ô]
Try
[ô]Verifica o certificado a ser utilizado na assinatura
Dim _xnome As String
Dim _X509Cert As X509Certificate2
Dim store As X509Store
Dim collection As X509Certificate2Collection
Dim collection1 As X509Certificate2Collection

_xnome = [Ô][Ô]

_xnome = pCertificado.Subject.ToString()

_X509Cert = New X509Certificate2()
store = New X509Store([Ô]MY[Ô], StoreLocation.CurrentUser)
store.Open(OpenFlags.ReadOnly Or OpenFlags.OpenExistingOnly)

collection = store.Certificates
collection1 = collection.Find(X509FindType.FindBySubjectDistinguishedName, _xnome, False)

If (collection1.Count = 0) Then
vResultado = 2
vResultadoString = [Ô]Problemas no certificado digital[Ô]
Else
[ô] certificado ok
_X509Cert = collection1.Item(0)
Dim x As String
x = _X509Cert.GetKeyAlgorithm().ToString()

[ô] Create a new XML document.
Dim doc As New XmlDocument
doc = New XmlDocument()

[ô]Format the document to ignore white spaces.
doc.PreserveWhitespace = False
[ô] Load the passed XML file using it’s name.
Try
doc.LoadXml(vXMLString)
[ô]doc.Save([Ô]C:\cte1.xml[Ô])

[ô] Verifica se a tag a ser assinada existe é única
Dim qtdeRefUri As Integer
qtdeRefUri = doc.GetElementsByTagName(pUri).Count

If (qtdeRefUri = 0) Then
[ô] a URI indicada não existe
vResultado = 4
vResultadoString = [Ô]A tag de assinatura [Ô] + pUri.Trim() + [Ô] não existe[Ô]

Else
[ô] Existe mais de uma tag a ser assinada
If (qtdeRefUri > 1) Then
[ô] existe mais de uma URI indicada
vResultado = 5
vResultadoString = [Ô]A tag de assinatura [Ô] + pUri.Trim() + [Ô] não é unica[Ô]
Else

Try
[ô] Create a SignedXml object.
Dim signedXml As SignedXml
signedXml = New SignedXml(doc)

[ô] Add the key to the SignedXml document
signedXml.SigningKey = _X509Cert.PrivateKey

[ô] Create a reference to be signed
Dim reference As New Reference
reference = New Reference()

[ô]--------- RETIRAR COMENTÁRIOS DAS LINHAS ABAIXO
[ô] pega o uri que deve ser assinada
Dim _Uri As XmlAttributeCollection
Dim _atributo As XmlAttribute

_Uri = doc.GetElementsByTagName(pUri).Item(0).Attributes
For Each _atributo In _Uri
If (_atributo.Name = [Ô]Id[Ô]) Then
reference.Uri = [Ô]#[Ô] + _atributo.InnerText

End If
Next

[ô] Add an enveloped transformation to the reference.
Dim env As New XmlDsigEnvelopedSignatureTransform
env = New XmlDsigEnvelopedSignatureTransform()
reference.AddTransform(env)

Dim c14 As New XmlDsigC14NTransform
c14 = New XmlDsigC14NTransform()
reference.AddTransform(c14)

[ô] Add the reference to the SignedXml object.
signedXml.AddReference(reference)

[ô] Create a new KeyInfo object
Dim keyinfo As New KeyInfo
keyinfo = New KeyInfo()

[ô] Load the certificate into a KeyInfoX509Data object
[ô] and add it to the KeyInfo object.
keyinfo.AddClause(New KeyInfoX509Data(_X509Cert))

[ô] Add the KeyInfo object to the SignedXml object.
signedXml.KeyInfo = keyinfo
signedXml.ComputeSignature()

[ô] Get the XML representation of the signature and save
[ô] it to an XmlElement object.
Dim xmlDigitalSignature As XmlElement
xmlDigitalSignature = signedXml.GetXml()

[ô] Gravar o elemento no documento XML
doc.DocumentElement.AppendChild(doc.ImportNode(xmlDigitalSignature, True))
XmlDoc = New XmlDocument()
XmlDoc.PreserveWhitespace = False
XmlDoc = doc

[ô] Atualizar a string do XML já assinada
vXMLStringAssinado = XmlDoc.OuterXml

[ô] Gravar o XML no HD
[ô] abre um stream para escrita e cria um StreamWriter para implementar o stream
Dim fs As New FileStream(pArqXMLAssinar, FileMode.OpenOrCreate, FileAccess.Write)
Dim SW_2 As New StreamWriter(fs)
SW_2.Flush()
SW_2.BaseStream.Seek(0, SeekOrigin.Begin)
SW_2.Write(vXMLStringAssinado)
SW_2.Flush()
SW_2.Close()
Catch ex As Exception
vResultado = 6
vResultadoString = [Ô]Erro ao assinar o documento - [Ô] + ex.Message

End Try

End If

End If

Catch ex As Exception

vResultado = 3
vResultadoString = [Ô]XML mal formado - [Ô] + ex.Message

End Try

End If

Catch ex As Exception

vResultado = 1
vResultadoString = [Ô]Problema ao acessar o certificado digital[Ô] + ex.Message

End Try

End Sub
KERPLUNK 14/05/2017 14:26:23
#473936
[ô]da erro[ô] é meio genérico demais, que erro?
MALA 14/05/2017 15:15:16
#473937
da esse erro (a conexao subjacente estava fechada, erro inesperado em um envio)
NILSONTRES 14/05/2017 19:34:34
#473940
Citação:

da esse erro (a conexao subjacente estava fechada, erro inesperado em um envio)


é Cartão ?
Pode ser o leitor ou o próprio cartão.
Essa mensagem não é de erro de sistema, mas sim de certificado. Cartão ou arquivo.
MALA 14/05/2017 22:07:48
#473943
Arquivo A1, mas o problema esta na função de assinar, pois tentei assinar com uma DLL de terceiro e passou normal, so da o erro quando assino com essa função ai acima
DS2T 14/05/2017 23:08:33
#473944
Em qual linha está dando o erro?
NILSONTRES 15/05/2017 07:47:51
#473945
Citação:

ATE SEXTA FUNCIONOU LEGAL, ONTEM COMEÇOU DA ERRO NA ASSINATURA


Se vc não fez alteração no código, então não é ele.
Tópico encerrado , respostas não são mais permitidas