Altair Absent Member.
Absent Member.
4007 views

Signature xml file

Jump to solution

I'm trying to convert a C # code that signer a xml file to vc2010 2.2. NET. I've searched the forum but have not found any examples of signature xml file.
Attached the code in C # and running the code in VC I'm trying to create. Someone from the forum could help me?

VC 2010 2.2 .NET

S.O. XP SP3

0 Likes
1 Solution

Accepted Solutions
Micro Focus Expert
Micro Focus Expert

RE: Signature xml file

Jump to solution

Something like the following:

      $set ilusing"System"
      $set ilusing"System.Windows.Forms"
      $set ilusing"System.Xml"
      $set ilusing"System.Security.Cryptography"
      $set ilusing"System.Security.Cryptography.Xml"
      $set ilusing"System.Security"
      $set ilusing"System.Security.Cryptography.X509Certificates"
       class-id testxmlsig.Form1 is partial
                 inherits type System.Windows.Forms.Form.
       
       working-storage section.
       
       method-id NEW.
       procedure division.
           invoke self::InitializeComponent
           goback.
       end method.

       method-id button1_Click final private.
       procedure division using by value sender as object e as type System.EventArgs.
       
           declare XMLAssinado as string = "c:\OutXML.xml"
           declare #XML as string = "c:\InXML.xml"
           declare pCertificado as type X509Certificate2 = null

           try
               *> verificando existencia de certificado utilizado na assinatura
              declare subject as string = type String::Empty
              if (pCertificado not = null)
                 set subject to pCertificado::Subject::ToString
              end-if
              declare x509Certificate as type X509Certificate2 = new X509Certificate2
              declare store as type X509Store = new X509Store("MY", type StoreLocation::CurrentUser)
              invoke store::Open(type OpenFlags::ReadOnly b-or type OpenFlags::OpenExistingOnly)
              declare collection as type X509Certificate2Collection = store::Certificates 
                 as type X509Certificate2Collection
              declare collection1 as type X509Certificate2Collection 
                 = collection::Find(type X509FindType::FindByTimeValid, type DateTime::Now, false) 
                   as type X509Certificate2Collection
              declare collection2 as type X509Certificate2Collection 
                 = collection::Find(type X509FindType::FindByKeyUsage, 
                   type X509KeyUsageFlags::DigitalSignature, false) as type X509Certificate2Collection
              declare scollection as type X509Certificate2Collection 
                 = type X509Certificate2UI::SelectFromCollection(collection2, 
                   "Certificado(s) Digital(is) disponível(is)", 
                   "Selecione o certificado digital para uso no aplicativo", 
                   type X509SelectionFlag::SingleSelection)
              if (scollection::Count = 0)
                 invoke type MessageBox::Show("Nenhum certificado digital foi selecionado ou o "
                    & "certificado selecionado está com problemas.")
              else
                 set pCertificado to scollection[0]
                 declare documento as type XmlDocument = new XmlDocument
                 set documento::PreserveWhitespace to true
                 try
                    *> verificando elemento de referencia
                    invoke documento::Load(#XML)
                    try
                       *> selecionando certificado digital baseado no subject
                       set x509Certificate to collection1[0]
                       declare docXML as type SignedXml = new SignedXml(documento)
                       set docXML::SigningKey to pCertificado::PrivateKey
                       *> Create a reference to be signed.
                       declare #reference as type Reference = new Reference()
                       set #reference::Uri to ""
                       *> adicionando EnvelopedSignatureTransform a referencia
                       declare envelopedSigntature as type XmlDsigEnvelopedSignatureTransform
                          = new XmlDsigEnvelopedSignatureTransform
                       invoke #reference::AddTransform(envelopedSigntature)
                       declare c14Transform as type XmlDsigC14NTransform = new XmlDsigC14NTransform
                       invoke #reference::AddTransform(c14Transform)
                       invoke docXML::AddReference(#reference)
                       *> carrega o certificado em KeyInfoX509Data para adicionar a KeyInfo
                       declare keyInfo as type KeyInfo = new KeyInfo
                       invoke keyInfo::AddClause(new type KeyInfoX509Data(pCertificado))
                       set docXML::KeyInfo to keyInfo
                       invoke docXML::ComputeSignature
                       *> recuperando a representacao do XML assinado
                       declare xmlDigitalSignature as type XmlElement = docXML::GetXml
                       invoke documento::DocumentElement::AppendChild(documento::ImportNode(xmlDigitalSignature, 
                          true))
                       set XMLAssinado to documento::OuterXml
                       invoke documento::Save("c:\OutXML.xml")
                    catch ex as type Exception
                       invoke type MessageBox::Show("Erro: " & ex::Message)
                    end-try
                 catch caught as type Exception
                    invoke type MessageBox::Show("Erro ao assinar o documento - " & caught::Message)
                 end-try
              end-if
           catch caught as type Exception 
              invoke type MessageBox::Show("XML mal formado - " & caught::Message)
           end-try.
            
       end method.
      
       end class.
0 Likes
7 Replies
Knowledge Partner
Knowledge Partner

RE: Signature xml file

Jump to solution

Did you forget to attach?


Tom Morrison
Consultant

0 Likes
Altair Absent Member.
Absent Member.

RE: Signature xml file

Jump to solution

Hi Tom Morrison,

Thanks for the feedback

The attached file assinaXML_C #. txt contains the two codes in C # running and below the that I wrote in VC.

0 Likes
Micro Focus Expert
Micro Focus Expert

RE: Signature xml file

Jump to solution

Something like the following:

      $set ilusing"System"
      $set ilusing"System.Windows.Forms"
      $set ilusing"System.Xml"
      $set ilusing"System.Security.Cryptography"
      $set ilusing"System.Security.Cryptography.Xml"
      $set ilusing"System.Security"
      $set ilusing"System.Security.Cryptography.X509Certificates"
       class-id testxmlsig.Form1 is partial
                 inherits type System.Windows.Forms.Form.
       
       working-storage section.
       
       method-id NEW.
       procedure division.
           invoke self::InitializeComponent
           goback.
       end method.

       method-id button1_Click final private.
       procedure division using by value sender as object e as type System.EventArgs.
       
           declare XMLAssinado as string = "c:\OutXML.xml"
           declare #XML as string = "c:\InXML.xml"
           declare pCertificado as type X509Certificate2 = null

           try
               *> verificando existencia de certificado utilizado na assinatura
              declare subject as string = type String::Empty
              if (pCertificado not = null)
                 set subject to pCertificado::Subject::ToString
              end-if
              declare x509Certificate as type X509Certificate2 = new X509Certificate2
              declare store as type X509Store = new X509Store("MY", type StoreLocation::CurrentUser)
              invoke store::Open(type OpenFlags::ReadOnly b-or type OpenFlags::OpenExistingOnly)
              declare collection as type X509Certificate2Collection = store::Certificates 
                 as type X509Certificate2Collection
              declare collection1 as type X509Certificate2Collection 
                 = collection::Find(type X509FindType::FindByTimeValid, type DateTime::Now, false) 
                   as type X509Certificate2Collection
              declare collection2 as type X509Certificate2Collection 
                 = collection::Find(type X509FindType::FindByKeyUsage, 
                   type X509KeyUsageFlags::DigitalSignature, false) as type X509Certificate2Collection
              declare scollection as type X509Certificate2Collection 
                 = type X509Certificate2UI::SelectFromCollection(collection2, 
                   "Certificado(s) Digital(is) disponível(is)", 
                   "Selecione o certificado digital para uso no aplicativo", 
                   type X509SelectionFlag::SingleSelection)
              if (scollection::Count = 0)
                 invoke type MessageBox::Show("Nenhum certificado digital foi selecionado ou o "
                    & "certificado selecionado está com problemas.")
              else
                 set pCertificado to scollection[0]
                 declare documento as type XmlDocument = new XmlDocument
                 set documento::PreserveWhitespace to true
                 try
                    *> verificando elemento de referencia
                    invoke documento::Load(#XML)
                    try
                       *> selecionando certificado digital baseado no subject
                       set x509Certificate to collection1[0]
                       declare docXML as type SignedXml = new SignedXml(documento)
                       set docXML::SigningKey to pCertificado::PrivateKey
                       *> Create a reference to be signed.
                       declare #reference as type Reference = new Reference()
                       set #reference::Uri to ""
                       *> adicionando EnvelopedSignatureTransform a referencia
                       declare envelopedSigntature as type XmlDsigEnvelopedSignatureTransform
                          = new XmlDsigEnvelopedSignatureTransform
                       invoke #reference::AddTransform(envelopedSigntature)
                       declare c14Transform as type XmlDsigC14NTransform = new XmlDsigC14NTransform
                       invoke #reference::AddTransform(c14Transform)
                       invoke docXML::AddReference(#reference)
                       *> carrega o certificado em KeyInfoX509Data para adicionar a KeyInfo
                       declare keyInfo as type KeyInfo = new KeyInfo
                       invoke keyInfo::AddClause(new type KeyInfoX509Data(pCertificado))
                       set docXML::KeyInfo to keyInfo
                       invoke docXML::ComputeSignature
                       *> recuperando a representacao do XML assinado
                       declare xmlDigitalSignature as type XmlElement = docXML::GetXml
                       invoke documento::DocumentElement::AppendChild(documento::ImportNode(xmlDigitalSignature, 
                          true))
                       set XMLAssinado to documento::OuterXml
                       invoke documento::Save("c:\OutXML.xml")
                    catch ex as type Exception
                       invoke type MessageBox::Show("Erro: " & ex::Message)
                    end-try
                 catch caught as type Exception
                    invoke type MessageBox::Show("Erro ao assinar o documento - " & caught::Message)
                 end-try
              end-if
           catch caught as type Exception 
              invoke type MessageBox::Show("XML mal formado - " & caught::Message)
           end-try.
            
       end method.
      
       end class.
0 Likes
Renato Absent Member.
Absent Member.

RE: Signature xml file

Jump to solution

Boa tarde Chris Glazier , qual tipo de projeto devo criar para funcionar esse programa, já tentei em vários e não deu certo, desculpe tanto questionamento, e que compramos agora o visual cobol for visual studio.

obrigado

Renato

0 Likes
Highlighted
Altair Absent Member.
Absent Member.

RE: Signature xml file

Jump to solution

Olá Renato, o projeto em questão é Windows Forms e você precisa referenciar o namespace System.Security. É necessário também que você tenha o certificado digital A3 plugado na máquina.

Hi Renato, the project in question is Windows Forms and you need to create a reference to the System.Security namespace. You must also have the A3 digital certificate plugged in your machine.

https://www.youtube.com/results?search_query=visual+cobol+altair+borges

0 Likes
Renato Absent Member.
Absent Member.

RE: Signature xml file

Jump to solution

Olá Altair, obrigado pela atenção, fiz o que você me passou, mas não deu certo, ainda não sabemos utilizar com o projeto do visual cobol for visual studio, pois compramos a um mês, e ainda estamos apanhando nisso, teria como me passar um passo a passo, agradeceria muito.

Obrigado

0 Likes
Renato Absent Member.
Absent Member.

RE: Signature xml file

Jump to solution
boa tarde Altair
depois de algum tempo, conseguimos voltar ao projeto por força de pressão, rsrs
conseguimos assinar o xml, porem ele utilizou o método de assinatura rsa-sha1, e precisamos do método rsa-sha256, como consigo alterar esse método.

obrigado

Renato
0 Likes
The opinions expressed above are the personal opinions of the authors, not of Micro Focus. By using this site, you accept the Terms of Use and Rules of Participation. Certain versions of content ("Material") accessible here may contain branding from Hewlett-Packard Company (now HP Inc.) and Hewlett Packard Enterprise Company. As of September 1, 2017, the Material is now offered by Micro Focus, a separately owned and operated company. Any reference to the HP and Hewlett Packard Enterprise/HPE marks is historical in nature, and the HP and Hewlett Packard Enterprise/HPE marks are the property of their respective owners.