Skip to main content

Notifications

Microsoft Dynamics 365 | Integration, Dataverse...
Unanswered

Sign Xml using plugin

(0) ShareShare
ReportReport
Posted on by 35
Hi,

I'm signing an XML for a plugin, but whenever I run the code, it returns an error.

Could someone help me, please.

Note: Certificate in pfx format.
Plugin is called via javascript



  • Felipe Kavai Profile Picture
    Felipe Kavai 35 on at
    RE: Sign Xml using plugin
    I inserted the certificate via xml. Just changing the extension, however PrivateKey is not returned and I not see other way to get the certificate, I tried to perform the query by the local machine but it returns the same error.

    Of course, here is the error that the system returns to me:

    error = {errorCode: 2147746340, message: "Erro inesperado no código ISV.", code: 2147746340, title: "O domínio especificado não existe ou não pode ser contatado", raw: "{"_errorCode":2147746340,"_errorFault":{"_response…textId":"eb7e193a-f37c-419f-a37f-971ec0d9e9d3"}}}"}

    To better explain the process, I have a code in C #, follow the code below:

    using Microsoft.Xrm.Sdk;
    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Text;
    using System.Threading.Tasks;
    using System.ComponentModel;
    using System.Data;
    using System.Drawing;
    
    using System.Security;
    using System.Security.Cryptography;
    using System.Security.Cryptography.X509Certificates;
    
    using System.ServiceModel;
    using System.ServiceModel.Description;
    using System.ServiceModel.Channels;
    using IntegraçãoTeste.psp;
    
    using System.Net;
    using System.Xml;
    using System.Security.Cryptography.Xml;
    using System.IO;
    using Microsoft.Xrm.Sdk.Messages;
    using Microsoft.Xrm.Sdk.Query;
    
    namespace IntegraçãoTeste
    {
        public class CustomAction : IPlugin
        {
            public void Execute(IServiceProvider serviceProvider)
            {        
                IPluginExecutionContext context = (IPluginExecutionContext)serviceProvider.GetService(typeof(IPluginExecutionContext));
                IOrganizationServiceFactory factory = (IOrganizationServiceFactory)serviceProvider.GetService(typeof(IOrganizationServiceFactory));
                IOrganizationService service = factory.CreateOrganizationService(context.UserId);
    
                RetrieveMultipleRequest rmr = new RetrieveMultipleRequest();
                RetrieveMultipleResponse resp = new RetrieveMultipleResponse();
                Entity wr = new Entity();
    
                QueryExpression query = new QueryExpression()
                {
                    EntityName = "webresource",
                    ColumnSet = new ColumnSet("content"),
                    Criteria = new FilterExpression
                    {
                        FilterOperator = LogicalOperator.And,
                        Conditions =
                                    {
                                        new ConditionExpression
                                        {
                                            AttributeName = "name",
                                            Operator = ConditionOperator.Equal,
                                            Values = { "new_Assinatura_Certificado" }
                                        }
                                    }
                    }
                };
    
                rmr.Query = query;
                resp = (RetrieveMultipleResponse)service.Execute(rmr);
                wr = (Entity)resp.EntityCollection.Entities[0];
                byte[] certbytes = Convert.FromBase64String(wr.Attributes["content"].ToString());
    
                X509Certificate2 cert1 = new X509Certificate2(certbytes, "b4teria2021");
    
                using (WebClient client = new WebClient())
                {
    
                XmlDocument doc = new XmlDocument();
                string req = "    999999999999    999999999999 ";
                doc.LoadXml(req);
                
                AssinaDocComCertificado(doc, cert1);
                
                StringWriter sw = new StringWriter();
                XmlTextWriter tx = new XmlTextWriter(sw);
                doc.WriteTo(tx);
                
                //string str = sw.ToString();
                string str = cert1.ToString();
            
                br.gov.sp.prefeitura.nfe.LoteNFe ws = new br.gov.sp.prefeitura.nfe.LoteNFe();
                ws.ClientCertificates.Add(cert1);
                Console.WriteLine(ws.ConsultaCNPJ(1, str));
                
                // I create this part to verify the cert
                    Entity contact = new Entity("contact");
                    contact["firstname"] = "Bob";
                    contact["lastname"] = "Smith";
                    contact["description"] = str;
                    Guid contactId = service.Create(contact);
                }
            }
            public static void AssinaDocComCertificado(XmlDocument doc, X509Certificate2 cert1)
            {
                SignedXml signedXml = new SignedXml(doc);
                signedXml.SigningKey = cert1.PrivateKey;
                Reference reference = new Reference();
                reference.Uri = "";
                reference.AddTransform(new XmlDsigEnvelopedSignatureTransform());
                signedXml.AddReference(reference);
    
                KeyInfo keyinfo = new KeyInfo();
                keyinfo.AddClause(new KeyInfoX509Data(cert1));
    
                signedXml.KeyInfo = keyinfo;
                signedXml.ComputeSignature();
                XmlElement xmlSig = signedXml.GetXml();
    
                doc.DocumentElement.AppendChild(doc.ImportNode(xmlSig, true));
            }
        }
    
    }

    It is called by a html, follows code below:

    
        
            
    
            
            
            
            
             
            
            
            
        
    
        
    
            
    
            
        
    

  • Nya Profile Picture
    Nya 29,058 on at
    RE: Sign Xml using plugin

    Hi,

    Would you please describe the error in more detail, e.g. with an error message, log or screenshot?

     

    Best Regards,

    Nya

Under review

Thank you for your reply! To ensure a great experience for everyone, your content is awaiting approval by our Community Managers. Please check back later.

Helpful resources

Quick Links

Announcing Our 2025 Season 1 Super Users!

A new season of Super Users has arrived, and we are so grateful for the daily…

Announcing Forum Attachment Improvements!

We're excited to announce that attachments for replies in forums and improved…

Vahid Ghafarpour – Community Spotlight

We are excited to recognize Vahid Ghafarpour as our February 2025 Community…

Leaderboard

#1
André Arnaud de Calavon Profile Picture

André Arnaud de Cal... 291,969 Super User 2025 Season 1

#2
Martin Dráb Profile Picture

Martin Dráb 230,842 Most Valuable Professional

#3
nmaenpaa Profile Picture

nmaenpaa 101,156

Leaderboard

Product updates

Dynamics 365 release plans