Zdrojové kódy pro vývojáře.
Přeskočit odkazy pro navigaci Top 10 přispěvatelů
UživatelČlánky
codeshare45
sochor1
stoupa1
tomas.oplt15
Článek: Digitální podpis XML dokumentů, ověření digitálního podpisu
Špatný Super
Autor:
Vytvořeno:
Popularita:

Úvod

Třída XMLSignature obsahuje dvě metody pro manipulaci s XML 

VerifyXMLSignature - ověří platnost XML dokumentu
SignXML - podepíše XML dokument


using System;
using System.Collections.Generic;
using System.Text;
using System.Xml;
using CAPICOM;
using System.Security.Cryptography.Xml;
using System.Security.Cryptography.X509Certificates;
using System.Security.Cryptography;
using System.IO;
using System.Collections;

namespace DigitalSignature
{

    public class XMLSignature
    {

        ///


        /// Verify XML document signature
        ///
        /// File path
        /// Certificate name in local certification store CAPICOM_CURRENT_USER_STORE
        ///
        public static bool VerifyXMLSignature(string xmlPath, string certificateName)
        {
            // Get certificate from store
            Certificate cert = XMLSignature.GetCertificateFromName(certificateName);
            if (cert == null)
                throw new ApplicationException("Cannot find certificate: " + certificateName);

            // Get certificate details
            string keyContainerName = cert.PrivateKey.ContainerName;
            bool canexp = cert.PrivateKey.IsExportable();
            int keyspec = (int)cert.PrivateKey.KeySpec;

            // Crypto parameters
            CspParameters cspParam = new CspParameters();
            cspParam.KeyContainerName = keyContainerName;
            cspParam.KeyNumber = keyspec;
            RSACryptoServiceProvider rsaProvider = new RSACryptoServiceProvider(cspParam);

            // Get public key - we need it for verification
            string strPublicKey = rsaProvider.ToXmlString(false);

            // Get RSA provider from public key            
            RSACryptoServiceProvider csp = new RSACryptoServiceProvider();
            csp.FromXmlString(strPublicKey);

            // Load XML signed document
            XmlDocument xmldoc = new XmlDocument();
            xmldoc.Load(xmlPath);

            // Create the signed XML document.
            SignedXml sxml = new SignedXml(xmldoc);

            try
            {
                // Get the XML Signature from document
                XmlNode dsig = xmldoc.GetElementsByTagName("Signature", SignedXml.XmlDsigNamespaceUrl)[0];
                sxml.LoadXml((XmlElement)dsig);
            }
            catch
            {
                // Signature not found ?
                return false;
            }

            // Verify ...
            if (sxml.CheckSignature(csp))
                return true;
            else
                return false;
        }

        ///


        /// Sign XML document
        ///
        ///
        ///
        public static void SignXML(string documentPath, string certificateName)
        {
            // Get certificate from store
            Certificate cert = XMLSignature.GetCertificateFromName(certificateName);
            if (cert == null)
                throw new ApplicationException("Cannot find certificate: " + certificateName);

            // Load XML document
            XmlDocument xmldoc = new XmlDocument();
            xmldoc.Load(documentPath);

            // Get certificate details
            string strKeyContainerName = cert.PrivateKey.ContainerName;
            int iKeyNum = (int)cert.PrivateKey.KeySpec;

            // Crypto parameters
            CspParameters cspParam = new CspParameters();
            cspParam.KeyContainerName = strKeyContainerName;
            cspParam.KeyNumber = iKeyNum;
            RSACryptoServiceProvider rsaProvider = new RSACryptoServiceProvider(cspParam);

            // Create signed document
            System.Security.Cryptography.Xml.SignedXml signedXML = new System.Security.Cryptography.Xml.SignedXml(xmldoc);
            signedXML.SigningKey = rsaProvider;

            signedXML.SignedInfo.CanonicalizationMethod = SignedXml.XmlDsigCanonicalizationUrl;

            // Empty reference
            Reference reference = new Reference("");

            reference.AddTransform(new XmlDsigEnvelopedSignatureTransform(false));

            // Add reference to signed document
            signedXML.AddReference(reference);

            // Compute the signature.
            signedXML.ComputeSignature();

            // Get XML signature  and add it to the document
            XmlElement sig = signedXML.GetXml();
            xmldoc.DocumentElement.AppendChild(sig);

            // Create signed document
            string xmlDocumentSigned = documentPath + ".sig";
         
            if (System.IO.File.Exists(xmlDocumentSigned) == true)
                System.IO.File.Delete(xmlDocumentSigned);

            XmlTextWriter writer = new XmlTextWriter(xmlDocumentSigned, Encoding.Default);
            writer.Formatting = Formatting.Indented;

            // Save document with signature
            try
            {
                xmldoc.WriteTo(writer);
            }
            finally
            {
                writer.Flush();
                writer.Close();
            }

        }

        ///


        /// Get certificate from store
        ///
        /// Certificate name
        ///
        public static Certificate GetCertificateFromName(string certificateName)
        {
            string storeName = "My";
            StoreClass oStore;
            Certificates oCerts;
            string filter = "";

            StringWriter sw = new StringWriter();
            oStore = new StoreClass();
            oStore.Open(CAPICOM_STORE_LOCATION.CAPICOM_CURRENT_USER_STORE, storeName, CAPICOM_STORE_OPEN_MODE.CAPICOM_STORE_OPEN_EXISTING_ONLY | CAPICOM_STORE_OPEN_MODE.CAPICOM_STORE_OPEN_READ_ONLY);
            oCerts = (Certificates)oStore.Certificates;
            oCerts = (Certificates)oCerts.Find(CAPICOM_CERTIFICATE_FIND_TYPE.CAPICOM_CERTIFICATE_FIND_SUBJECT_NAME, filter, false);

            foreach (Certificate certificate in oCerts)
            {
                if ( certificate.SubjectName == certificateName )
                {
                        return certificate;
                }
            }

            return null;
        }
    }

}

  Na stránku 
screen  Nový příspěvek
Název  Uživatel  Datum 
Poslední návštěva: 20:49:02, 22. září 2017 První  Předchozí  0 Záznamů  Další  Poslední  

Autor článku
Jméno
Pracovní pozice
Informace
Foto

   

Počet návštěvníků:51
 
  Kontakt