コード例 #1
0
        private void cmdCheckSignature_Click(object sender, EventArgs e)
        {
            if (string.IsNullOrWhiteSpace(txtSignedPayloadFile.Text))
            {
                // files validation
                MessageBox.Show("The Signed Payload File was not specified!", Text, MessageBoxButtons.OK, MessageBoxIcon.Warning);
                return;
            }

            // register SHA-256 and open certificate with exportable private key
            CryptoConfig.AddAlgorithm(typeof(RSAPKCS1SHA256SignatureDescription), RSAPKCS1SHA256SignatureDescription.SignatureMethod);

            //Check the signature to make sure it is valid, this requires the KeyInfo to be present
            //This should be commented out if not using the KeyInfo in the XmlManager class

            try{
                bool result = XmlManager.CheckSignature(txtSignedPayloadFile.Text);
                if (result == false)
                {
                    MessageBox.Show("Signature is not valid!", Text, MessageBoxButtons.OK, MessageBoxIcon.Warning);
                }
                else
                {
                    MessageBox.Show("Signature is valid!", Text, MessageBoxButtons.OK, MessageBoxIcon.Warning);
                }
            }
            catch (Exception ex)
            {
                ex.DisplayException(Text);
                return;
            }
        }
コード例 #2
0
        /// <summary>
        /// Static constructor to add xmldsig-filter2 and apply nodelist fixes
        /// </summary>
        static Xades()
        {
            CryptoConfig.AddAlgorithm(typeof(XmlDsigFilterTransform), XmlDsigFilterTransform.AlgorithmURI);

            _checkSignedInfo    = (CheckSignedInfoDelegate)typeof(SignedXml).GetMethod("CheckSignedInfo", BindingFlags.NonPublic | BindingFlags.Instance, null, new Type[] { typeof(AsymmetricAlgorithm) }, null).CreateDelegate(typeof(CheckSignedInfoDelegate));
            _calculateHashValue = typeof(Reference).GetMethod("CalculateHashValue", BindingFlags.NonPublic | BindingFlags.Instance);
        }
コード例 #3
0
ファイル: Program.cs プロジェクト: HackerDom/ructfe-2017
        private static void Main()
        {
            CryptoConfig.AddAlgorithm(typeof(RHHE), RHHE.Name);

            string line;

            while ((line = Console.ReadLine()) != null)
            {
                var parts = line.Split('\t');
                if (parts.Length != 3)
                {
                    Console.Error.WriteLine($"bad line '{line}'");
                    continue;
                }

                var login    = parts[0];
                var hash     = parts[1];
                var newLogin = parts[2];

                if (login.Length != newLogin.Length)
                {
                    Console.Error.WriteLine($"length of old login '{login}' is not equal to length of new login '{newLogin}'");
                    continue;
                }

                var oldFakeHash = GetHmac(login);
                var newFakeHash = GetHmac(newLogin);

                var diff         = oldFakeHash.Zip(newFakeHash, (b1, b2) => (byte)(b1 ^ b2)).ToArray();
                var hashBytes    = Convert.FromBase64String(hash.Replace('-', '+').Replace('_', '/'));
                var newHashBytes = hashBytes.Zip(diff, (b1, b2) => (byte)(b1 ^ b2)).ToArray();
                var newHash      = Convert.ToBase64String(newHashBytes).Replace('+', '-').Replace('/', '_');
                Console.WriteLine(newHash);
            }
        }
コード例 #4
0
        public static SignedXml Extended(XmlDocument doc)
        {
            var signatureMethod = @"http://www.w3.org/2001/04/xmldsig-more#rsa-sha256";

            CryptoConfig.AddAlgorithm(typeof(DSSSignatureDescription), signatureMethod);

            var signedXml = new SignedXml(doc)
            {
                SigningKey = new DSS(),
            };

            signedXml.SignedInfo.SignatureMethod = signatureMethod;

            signedXml.SignedInfo.CanonicalizationMethod = SignedXml.XmlDsigExcC14NTransformUrl;

            // Create a reference to be signed.
            Reference reference = new Reference();

            reference.Uri = "";

            // Add an enveloped transformation to the reference.
            XmlDsigEnvelopedSignatureTransform env = new XmlDsigEnvelopedSignatureTransform();

            reference.AddTransform(env);

            // Add the reference to the SignedXml object.
            signedXml.AddReference(reference);

            signedXml.ComputeSignature();

            return(signedXml);
        }
コード例 #5
0
 private static void AddSignatureMethodToCryptoApi(string signatureMethod)
 {
     if (CryptoConfig.CreateFromName(signatureMethod) == null)
     {
         CryptoConfig.AddAlgorithm(typeof(RsaPkCs1Sha256SignatureDescription), signatureMethod);
     }
 }
コード例 #6
0
        private static void ConfigureCryptoNameMapping(XElement cryptoNameMapping)
        {
            var typeAliases = (
                from cryptoClass in cryptoNameMapping
                .Elements(XName.Get("cryptoClasses"))
                .Elements(XName.Get("cryptoClass"))
                let attribute = cryptoClass.Attributes().FirstOrDefault()
                                where attribute?.Value != null
                                let type = Type.GetType(attribute.Value, false, false)
                                           where type != null
                                           select(Key: attribute.Name.LocalName, Value: type))
                              .ToDictionary(x => x.Key, x => x.Value);

            var nameMappings =
                from nameEntry in cryptoNameMapping.Elements(XName.Get("nameEntry"))
                let friendlyName = nameEntry.Attribute(XName.Get("name"))?.Value
                                   let className = nameEntry.Attribute(XName.Get("class"))?.Value
                                                   where friendlyName != null && className != null
                                                   let type = typeAliases.TryGetValue(className, out var value) ? value : null
                                                              where type != null
                                                              group friendlyName by type into items
                                                              select items;

            foreach (var items in nameMappings)
            {
                CryptoConfig.AddAlgorithm(items.Key, items.ToArray());
            }
        }
コード例 #7
0
        private static void Main()
        {
            XmlConfigurator.Configure();
            try
            {
                var settings = SimpleSettings.Create("settings");

                CryptoConfig.AddAlgorithm(typeof(RHHE), RHHE.Name);

                var sleepPeriod = int.Parse(settings.GetValue("sleep"));
                var ttl         = int.Parse(settings.GetValue("ttl"));

                var server   = PrepareServer(settings);
                var wsServer = PrepareWsServer(settings);

                SecretHolder.Init(settings.GetValue("secret"));
                CredentialsHolder.Init(settings.GetValue("credentials"), sleepPeriod);
                PointHolder.Init(settings.GetValue("points"), sleepPeriod, ttl, (point, msg) => wsServer.BroadcastAsync(point, msg, CancellationToken.None));

                Task
                .WhenAll(
                    server.AcceptLoopAsync(CancellationToken.None),
                    wsServer.AcceptLoopAsync(CancellationToken.None)
                    )
                .Wait();
            }
            catch (Exception ex)
            {
                Console.Error.WriteLine(ex);
                Log.Fatal("Unexpected exception", ex);
                Environment.Exit(ex.HResult == 0 ? ex.HResult : -1);
            }
        }
コード例 #8
0
        public static void GlobalEnableSha256XmlSignatures()
        {
            CryptoConfig.AddAlgorithm(typeof(ManagedSHA256SignatureDescription), RsaSha256Uri);

            AddAlgorithmIfMissing((IList <string>)XmlHelpers.KnownSigningAlgorithms, RsaSha256Uri);
            AddAlgorithmIfMissing((IList <string>)XmlHelpers.DigestAlgorithms, Sha256Uri);
        }
コード例 #9
0
        static XmlSecurity()
        {
            SchemaSet = new XmlSchemaSet();

            var currentType = typeof(XmlSecurity);

            Debug.Assert(currentType.Namespace != null, "currentType.Namespace != null");
            var typeNamespace = currentType.Namespace.Substring(0, currentType.Namespace.LastIndexOf("Security", StringComparison.Ordinal)) + "Xml";

            foreach (var pair in TypeSchemaMapping)
            {
                var xmlRoot = (XmlTypeAttribute)Attribute.GetCustomAttribute(pair.Key, typeof(XmlTypeAttribute));

                if (!SchemaSet.Contains(xmlRoot.Namespace))
                {
                    using (var stream = currentType.Assembly.GetManifestResourceStream(typeNamespace + "." + pair.Value))
                    {
                        if (stream == null)
                        {
                            throw new Exception(string.Format("Error on getting resource {0}.{1}", typeNamespace, pair.Value));
                        }

                        stream.Position = 0;
                        SchemaSet.Add(xmlRoot.Namespace, XmlReader.Create(stream));
                    }
                }
            }

            SchemaSet.Compile();

            // this prevents an exception: SignatureDescription could not be created for the signature algorithm supplied.
            // Apparently System.Security.Cryptography.Xml.SignedXml can't deal with SHA256 by default
            CryptoConfig.AddAlgorithm(typeof(RSAPKCS1SHA256SignatureDescription), "http://www.w3.org/2001/04/xmldsig-more#rsa-sha256");
        }
    public static void Main(String[] args)
    {
        //calculate caninicalized xml

        var         t   = new XmlDsigEnvelopedSignatureTransform(false);
        XmlDocument doc = new XmlDocument();

        //doc.PreserveWhitespace = true;
        doc.Load(@"c:\temp\x.xml");
        t.LoadInput(doc);


        FieldInfo field = t.GetType().GetField("_signaturePosition",
                                               BindingFlags.NonPublic |
                                               BindingFlags.Instance);


        field.SetValue(t, 1);

        var res = (XmlDocument)t.GetOutput();
        var s   = res.OuterXml;

        var c14 = new XmlDsigC14NTransform();

        c14.LoadInput(res);
        var mem = (MemoryStream)c14.GetOutput();

        var sha = new SHA256Managed();

        var byte1   = c14.GetDigestedOutput(new SHA256Managed());
        var digest1 = Convert.ToBase64String(byte1);
        var byte2   = sha.ComputeHash(mem.ToArray());
        var digest2 = Convert.ToBase64String(byte2);


        var s1      = System.Text.Encoding.UTF8.GetString(mem.ToArray());
        var byte3   = sha.ComputeHash(System.Text.Encoding.UTF8.GetBytes(s1));
        var digest3 = Convert.ToBase64String(byte3);

        //return;



        //validate signature

        CryptoConfig.AddAlgorithm(typeof(RSAPKCS1SHA256SignatureDescription), "http://www.w3.org/2001/04/xmldsig-more#rsa-sha256");
        XmlDocument xmlDoc = new XmlDocument();

        xmlDoc.Load(@"c:\temp\x.xml");
        XmlNode          node    = xmlDoc.DocumentElement;
        X509Certificate2 cert    = new X509Certificate2(File.ReadAllBytes(@"c:\temp\x.cer"));
        bool             isValid = ValidateXml(xmlDoc, cert);
        //return;


        //calc hash
        var sha1 = new SHA256Managed();
        var b1   = sha1.ComputeHash(System.Text.Encoding.UTF8.GetBytes(File.ReadAllText(@"c:\temp\x_no_sig.xml")));
        var b64  = Convert.ToBase64String(b1);
    }
コード例 #11
0
 static CryptoStrategy()
 {
     CryptoConfig.AddAlgorithm(typeof(AttachmentCiphertextTransform), AttachmentCiphertextTransform.Url);
     CryptoConfig.AddAlgorithm(typeof(AesGcmAlgorithm), "http://www.w3.org/2009/xmlenc11#aes128-gcm");
     CryptoConfig.AddAlgorithm(typeof(AesGcmAlgorithm), "http://www.w3.org/2009/xmlenc11#aes192-gcm");
     CryptoConfig.AddAlgorithm(typeof(AesGcmAlgorithm), "http://www.w3.org/2009/xmlenc11#aes256-gcm");
 }
コード例 #12
0
ファイル: Extensions.cs プロジェクト: ITLec/Dynamics-365-XEP
        public static void UsePortalsAuthentication <TUser>(this IAppBuilder app, StartupSettingsManager <TUser> manager)
            where TUser : CrmUser
        {
            CryptoConfig.AddAlgorithm(typeof(RSAPKCS1SHA256SignatureDescription), "http://www.w3.org/2001/04/xmldsig-more#rsa-sha256");

            if (manager.MicrosoftAccount != null)
            {
                app.UseMicrosoftAccountAuthentication(manager.MicrosoftAccount);
            }
            if (manager.Twitter != null)
            {
                app.UseTwitterAuthentication(manager.Twitter);
            }
            if (manager.Facebook != null)
            {
                app.UseFacebookAuthentication(manager.Facebook);
            }
            if (manager.Google != null)
            {
                app.UseGoogleAuthentication(manager.Google);
            }

            if (manager.LinkedIn != null)
            {
                app.UseLinkedInAuthentication(manager.LinkedIn);
            }
            if (manager.Yahoo != null)
            {
                app.UseYahooAuthentication(manager.Yahoo);
            }

            if (manager.WsFederationOptions != null)
            {
                foreach (var options in manager.WsFederationOptions)
                {
                    app.UseWsFederationAuthentication(options);
                }
            }

            if (manager.Saml2Options != null)
            {
                foreach (var options in manager.Saml2Options)
                {
                    app.UseSaml2Authentication(options);
                }
            }

            if (manager.OpenIdConnectOptions != null)
            {
                foreach (var options in manager.OpenIdConnectOptions)
                {
                    app.UseOpenIdConnectAuthentication(options);
                }
            }

            if (manager.AzureAdOptions != null)
            {
                app.UseOpenIdConnectAuthentication(manager.AzureAdOptions);
            }
        }
コード例 #13
0
        private static void Method2()
        {
            Console.WriteLine("Press enter to start the test");
            Console.ReadLine();
            CryptoConfig.AddAlgorithm(typeof(RSAPKCS1SHA256SignatureDescription), "http://www.w3.org/2001/04/xmldsig-more#rsa-sha256");

            // Create a new XML document.
            XmlDocument doc = new XmlDocument();

            // Format the document to ignore white spaces.
            doc.PreserveWhitespace = false;
            // Load the passed XML
            string my_xml = "<root><test>test</test></root>";

            doc.LoadXml(my_xml);

            ING.iDealAdvanced.Connector conn = new ING.iDealAdvanced.Connector();

            X509Certificate2         cert = conn.ClientCertificate;
            RSACryptoServiceProvider key  = null;// conn.GetMerchantRSACryptoServiceProvider();

            XmlSignature.Sign(ref doc, key, cert.Thumbprint);

            Console.WriteLine(doc.OuterXml);
            Console.WriteLine("");
            Console.WriteLine("");
            Console.WriteLine("");
            Console.WriteLine("Ended");
            Console.ReadLine();
        }
コード例 #14
0
        public AssinadorXML(DispatcherHelper dispatcher, ProgressBar progressBar = null)
        {
            this.dispatcher  = dispatcher;
            this.progressBar = progressBar;

            CryptoConfig.AddAlgorithm(typeof(RSAPKCS1SHA256SignatureDescription), signatureMethod);
        }
コード例 #15
0
ファイル: Program.cs プロジェクト: arturosantos/el-bebe
        static void Main(string[] args)
        {
            // .NET does not support SHA256-RSA2048 signature verification by default,
            // so register this algorithm for verification.
            CryptoConfig.AddAlgorithm(typeof(RSAPKCS1SHA256SignatureDescription),
                                      "http://www.w3.org/2001/04/xmldsig-more#rsa-sha256");

            // Load the receipt that needs to be verified as an XML document
            XmlDocument xmlDoc = new XmlDocument();

            xmlDoc.Load("..\\..\\receipt.xml");

            // The certificateId attribute is present in the document root, retrieve it
            XmlNode node          = xmlDoc.DocumentElement;
            string  certificateId = node.Attributes["CertificateId"].Value;

            // Retrieve the certificate from the official site.
            // NOTE: For sake of performance, you would want to cache this certificate locally.
            //       Otherwise, every single call will incur the delay of certificate retrieval.
            X509Certificate2 verificationCertificate = RetrieveCertificate(certificateId);

            try
            {
                // Validate the receipt with the certificate retrieved earlier
                bool isValid = ValidateXml(xmlDoc, verificationCertificate);
                System.Console.WriteLine("Certificate valid: " + isValid);
            }
            catch (Exception ex)
            {
                System.Console.WriteLine(ex.ToString());
            }
        }
コード例 #16
0
        public static void AddAlgorithm <T>(params string[] names)
        {
            var type = typeof(T);

            if (names != null)
            {
                foreach (var name in names)
                {
                    NameToType.Add(name, type);
                    CryptoConfig.AddAlgorithm(type, name);
                }
            }

            NameToType.Add(type.Name, type);
            CryptoConfig.AddAlgorithm(type, type.Name);

            if (type.FullName != null)
            {
                NameToType.Add(type.FullName, type);
                CryptoConfig.AddAlgorithm(type, type.FullName);
            }

            if (type.AssemblyQualifiedName != null)
            {
                NameToType.Add(type.AssemblyQualifiedName, type);
                CryptoConfig.AddAlgorithm(type, type.AssemblyQualifiedName);
            }
        }
コード例 #17
0
 static Saml2Signer()
 {
     CryptoConfig.AddAlgorithm(typeof(RSAPKCS1SHA1SignatureDescription), Saml2SecurityAlgorithms.RsaSha1Signature);
     CryptoConfig.AddAlgorithm(typeof(RSAPKCS1SHA256SignatureDescription), Saml2SecurityAlgorithms.RsaSha256Signature);
     CryptoConfig.AddAlgorithm(typeof(RSAPKCS1SHA384SignatureDescription), Saml2SecurityAlgorithms.RsaSha384Signature);
     CryptoConfig.AddAlgorithm(typeof(RSAPKCS1SHA512SignatureDescription), Saml2SecurityAlgorithms.RsaSha512Signature);
 }
        internal new void ComputeSignature()
        {
            var customerSigner = new CustomSigner();

            CryptoConfig.AddAlgorithm(typeof(cli_exakvdocsign.RSAPKCS1SHA256SignatureDescription), "http://www.w3.org/2001/04/xmldsig-more#rsa-sha256");

            var methodInfo = typeof(SignedXml).GetMethod("BuildDigestedReferences",
                                                         BindingFlags.Instance | BindingFlags.NonPublic);

            methodInfo.Invoke(this, null);
            SignedInfo.SignatureMethod = "http://www.w3.org/2001/04/xmldsig-more#rsa-sha256";
            //See if there is a signature description class defined in the Config file
            SignatureDescription signatureDescription =
                CryptoConfig.CreateFromName(SignedInfo.SignatureMethod) as SignatureDescription;

            if (signatureDescription == null)
            {
                throw new CryptographicException("Cryptography_Xml_SignatureDescriptionNotCreated");
            }

            var hashAlg = signatureDescription.CreateDigest();

            if (hashAlg == null)
            {
                throw new CryptographicException("Cryptography_Xml_CreateHashAlgorithmFailed");
            }
            var methodInfo2 = typeof(SignedXml).GetMethod("GetC14NDigest", BindingFlags.Instance | BindingFlags.NonPublic);
            var hashvalue   = (byte[])methodInfo2.Invoke(this, new object[] { hashAlg });

            m_signature.SignatureValue = customerSigner.Sign(hashvalue);;
        }
コード例 #19
0
        static XmlProcessor()
        {
            SchemaSet = new XmlSchemaSet();

            var currentType   = typeof(XmlProcessor);
            var typeNamespace = currentType.Namespace;// .Substring(0,currentType.Namespace.LastIndexOf("XML.", StringComparison.Ordinal));// + "Xml";


            foreach (var pair in TypeSchemaMapping)
            {
                var xmlRoot = (XmlTypeAttribute)Attribute.GetCustomAttribute(pair.Key, typeof(XmlTypeAttribute));

                if (!SchemaSet.Contains(xmlRoot.Namespace))
                {
                    using (var stream = typeof(XmlProcessor).Assembly.GetManifestResourceStream($"{typeNamespace}." + pair.Value))
                    {
                        SchemaSet.Add(xmlRoot.Namespace, XmlReader.Create(stream));
                    }
                }
            }

            SchemaSet.Compile();

            // this prevents an exception: SignatureDescription could not be created for the signature algorithm supplied.
            // Apparently System.Security.Cryptography.Xml.SignedXml can't deal with SHA256 by default
            CryptoConfig.AddAlgorithm(typeof(RSAPKCS1SHA256SignatureDescription), "http://www.w3.org/2001/04/xmldsig-more#rsa-sha256");
        }
コード例 #20
0
 /// <summary>
 ///     Register crypto algorithms
 /// </summary>
 public static void RegisterCryptoAlgorithms()
 {
     foreach (XmlDsigSigningConfig config in XmlDsigconfigList.Values)
     {
         CryptoConfig.AddAlgorithm(config.SignatureDescription, config.SignatureMethod);
     }
 }
コード例 #21
0
ファイル: mansign2.cs プロジェクト: maoxingda/msbuild-1
        private void init()
        {
            CryptoConfig.AddAlgorithm(typeof(RSAPKCS1SHA256SignatureDescription),
                                      Sha256SignatureMethodUri);

            CryptoConfig.AddAlgorithm(typeof(System.Security.Cryptography.SHA256Cng),
                                      Sha256DigestMethod);
        }
コード例 #22
0
 public void Initialize()
 {
     CryptoConfig.AddAlgorithm(typeof(SHA256CryptoServiceProvider), "Rijndael",
                               "System.Security.Cryptography.Rijndael", "System.Security.Cryptography.RijndaelManaged");
     CryptoConfig.AddAlgorithm(typeof(SHA256CryptoServiceProvider), "MD5",
                               "System.Security.Cryptography.MD5", "System.Security.Cryptography.MD5CryptoServiceProvider",
                               "System.Security.Cryptography.MD5Managed");
 }
コード例 #23
0
ファイル: Saml.cs プロジェクト: pdo9141/SamlTester
 public static void Init()
 {
     if (!_initialized)
     {
         CryptoConfig.AddAlgorithm(typeof(RSAPKCS1SHA256SignatureDescription), "http://www.w3.org/2001/04/xmldsig-more#rsa-sha256");
     }
     _initialized = true;
 }
コード例 #24
0
        private void SetSigningAlgorithm(string signingAlgorithm)
        {
            var algorithm = SignatureAlgorithmProvider.Get(signingAlgorithm);

            SignedInfo.SignatureMethod = algorithm.GetIdentifier();

            CryptoConfig.AddAlgorithm(algorithm.GetType(), algorithm.GetIdentifier());
        }
コード例 #25
0
        public Validator(XmlDocument serviceRequest)
        {
            CryptoConfig.AddAlgorithm(typeof(RsaSha256SignatureDescription), @"http://www.w3.org/2001/04/xmldsig-more#rsa-sha256");

            document = serviceRequest;
            manager  = new NamespaceManager(document);
            RemoveValidSignatureElements = false;
        }
コード例 #26
0
ファイル: Turing.cs プロジェクト: fattyhan/TuringCipher.NET
        public static void Register()
        {
            //$ TODO: Need to figure out how to automatically register

            foreach (var kvp in s_implementations)
            {
                CryptoConfig.AddAlgorithm(kvp.Value, kvp.Key);
            }
        }
コード例 #27
0
ファイル: ECDSAConfig.cs プロジェクト: egelke/eHI
 static ECDSAConfig()
 {
     CryptoConfig.AddAlgorithm(typeof(ECDSASignatureFormatter), nameof(ECDSASignatureFormatter));
     CryptoConfig.AddAlgorithm(typeof(ECDSASignatureDeformatter), nameof(ECDSASignatureDeformatter));
     CryptoConfig.AddAlgorithm(typeof(ECDSASha1SignatureDescription), "http://www.w3.org/2001/04/xmldsig-more#ecdsa-sha1");
     CryptoConfig.AddAlgorithm(typeof(ECDSASha256SignatureDescription), "http://www.w3.org/2001/04/xmldsig-more#ecdsa-sha256");
     CryptoConfig.AddAlgorithm(typeof(ECDSASha384SignatureDescription), "http://www.w3.org/2001/04/xmldsig-more#ecdsa-sha384");
     CryptoConfig.AddAlgorithm(typeof(ECDSASha512SignatureDescription), "http://www.w3.org/2001/04/xmldsig-more#ecdsa-sha512");
 }
コード例 #28
0
        private static void AddRsaSha256AlgorithmToCryptoConfig()
        {
            const string signatureMethod = "http://www.w3.org/2001/04/xmldsig-more#rsa-sha256";

            if (CryptoConfig.CreateFromName(signatureMethod) == null)
            {
                CryptoConfig.AddAlgorithm(typeof(RsaPkCs1Sha256SignatureDescription), signatureMethod);
            }
        }
コード例 #29
0
        /// <summary>
        /// Verified the xml with the physical Certificate
        /// </summary>
        /// <param name="xmlDoc"> xml document</param>
        /// <param name="certificateFileName"> Certificate File Name</param>
        /// <returns>Boolean Value</returns>
        public static bool IsXmlSignValidByFile(XmlDocument xmlDoc, string certificateFileName)
        {
            CryptoConfig.AddAlgorithm(typeof(Security.Cryptography.RSAPKCS1SHA256SignatureDescription), "http://www.w3.org/2001/04/xmldsig-more#rsa-sha256");
            CspParameters cspParams = new CspParameters();

            cspParams.KeyContainerName = "XML_DSIG_RSA_KEY";
            RSACryptoServiceProvider csp = new RSACryptoServiceProvider(cspParams);

            if (xmlDoc == null)
            {
                throw new CryptographicException("XML Document object cann't be null");
            }

            X509Certificate2 x509;

            // Add SHA-256 algorith mapping.
            CryptoConfig.AddAlgorithm(typeof(Security.Cryptography.RSAPKCS1SHA256SignatureDescription), XmlDsigSha256SignatureMethod);

            // Create a new x509 instance based on the passed in certificate.
            try
            {
                x509 = new X509Certificate2(certificateFileName, string.Empty, X509KeyStorageFlags.Exportable);
            }
            catch
            {
                throw new CryptographicException("Could not load the certificate file at " + certificateFileName);
            }

            // loading the key string
            csp.FromXmlString(x509.PublicKey.Key.ToXmlString(false));
            xmlDoc.PreserveWhitespace = true;

            SignedXml signedXml = new SignedXml(xmlDoc);

            signedXml.SignedInfo.CanonicalizationMethod = SignedXml.XmlDsigCanonicalizationUrl;
            signedXml.SignedInfo.SignatureMethod        = "http://www.w3.org/2001/04/xmldsig-more#rsa-sha256";
            signedXml.SigningKey = csp;

            // Create a reference to be signed.
            Reference reference = new Reference(string.Empty);

            reference.DigestMethod = "http://www.w3.org/2001/04/xmlenc#sha256";

            // Add an enveloped transformation to the reference.
            XmlDsigEnvelopedSignatureTransform env = new XmlDsigEnvelopedSignatureTransform(false);

            reference.AddTransform(env);
            signedXml.AddReference(reference);

            // Find the "Signature" node and create a new
            XmlNodeList nodeList = xmlDoc.GetElementsByTagName("Signature");

            // Load the first <signature> node.
            signedXml.LoadXml((XmlElement)nodeList[0]);

            return(signedXml.CheckSignature(csp));
        }
コード例 #30
0
ファイル: XadesVerifier.cs プロジェクト: egelke/xades
        static XadesVerifier()
        {
            ECDSAConfig.Init();
            CryptoConfig.AddAlgorithm(typeof(OptionalDeflateTransform), OptionalDeflateTransform.AlgorithmUri);
#if NETSTANDARD
            CryptoConfig.AddAlgorithm(typeof(XmlDsigC14NTransform), "http://www.w3.org/TR/2001/REC-xml-c14n-20010315");
            CryptoConfig.AddAlgorithm(typeof(XmlDsigExcC14NTransform), "http://www.w3.org/2001/10/xml-exc-c14n#");
#endif
        }