View Single Post
  #1 (permalink)  
Old June 15th, 2014, 09:11 AM
romulus001 romulus001 is offline
Registered User
Points: 15, Level: 1
Points: 15, Level: 1 Points: 15, Level: 1 Points: 15, Level: 1
Activity: 0%
Activity: 0% Activity: 0% Activity: 0%
 
Join Date: Jun 2014
Posts: 3
Thanks: 0
Thanked 0 Times in 0 Posts
Default Signing an xml document with a certificate

Hello everyone,

I need to sign this xml file with a x509 v3 certificate but the signature must be at affixed there:

Invoice/ext:UBLExtensions/ext:UBLExtension/ext:ExtensionContent (lines 19-20)

I found a code to sign an xml file but it's affixed at the end of the document, how shall i proceed?

Here is my code:

Code:
Dim f_adresse As String = System.AppDomain.CurrentDomain.BaseDirectory
Dim f_temp As String = f_adresse & "TEMP\"
Dim f_fichier As String = "20381235051-01-FF11-04.xml"
Dim f_certificat As String = f_adresse & "aG9CcVpHVndCWTd3WlVOVw==.p12"
Dim f_pwd As String = "xxxxxxxxxxxxxxxx"
 
Dim xmlFile As String = f_temp & f_fichier
 
Dim MonCertificat As X509Certificate2 = New X509Certificate2(f_certificat, f_pwd)
 
Dim xmlDoc As XmlDocument = New XmlDocument()
xmlDoc.PreserveWhitespace = True
xmlDoc.Load(xmlFile)
 
Dim signedXml As SignedXml = New SignedXml(xmlDoc)
 
Dim KeyInfo As KeyInfo = New KeyInfo()
Dim Reference As Reference = New Reference()
Reference.Uri = ""
 
Reference.AddTransform(New XmlDsigEnvelopedSignatureTransform())
 
signedXml.AddReference(Reference)
 
Dim X509Chain As X509Chain = New X509Chain()
X509Chain.Build(MonCertificat)
 
Dim local_element As X509ChainElement = X509Chain.ChainElements(0)
Dim x509Data As KeyInfoX509Data = New KeyInfoX509Data(local_element.Certificate)
Dim subjectName As String = local_element.Certificate.Subject
 
x509Data.AddSubjectName(subjectName)
KeyInfo.AddClause(x509Data)
 
signedXml.KeyInfo = KeyInfo
signedXml.ComputeSignature()
 
Dim signature As XmlElement = signedXml.GetXml()
 
For Each node As XmlNode In signature.SelectNodes("descendant-or-self::*[namespace-uri()='http://www.w3.org/2000/09/xmldsig#']")
    node.Prefix = "ds"
    If node.LocalName = "Signature" Then
        Dim newAttribute As XmlAttribute = xmlDoc.CreateAttribute("Id")
        newAttribute.Value = "SignatureSP"
        node.Attributes.Append(newAttribute)
     End If
Next node
 
xmlDoc.DocumentElement.AppendChild(xmlDoc.ImportNode(signature, True))
xmlDoc.Save(xmlFile)
Thanks
Reply With Quote