public void Deformatter()
        {
            AsymmetricSignatureDeformatter def = null;

            // Deformatter with all properties null
            try {
                def = sig.CreateDeformatter(dsa);
                Assert.Fail("Expected ArgumentNullException but got none");
            }
            catch (ArgumentNullException) {
                // this is what we expect
            }
            catch (Exception e) {
                Assert.Fail("Expected ArgumentNullException but got: " + e.ToString());
            }
            // Deformatter with invalid DeformatterAlgorithm property
            sig.DeformatterAlgorithm = "DSA";
            try {
                def = sig.CreateDeformatter(dsa);
                Assert.Fail("Expected InvalidCastException but got none");
            }
            catch (InvalidCastException) {
                // this is what we expect
            }
            catch (Exception e) {
                Assert.Fail("Expected InvalidCastException but got: " + e.ToString());
            }
            // Deformatter with valid DeformatterAlgorithm property
            sig.DeformatterAlgorithm = "DSASignatureDeformatter";
            try {
                def = sig.CreateDeformatter(dsa);
                Assert.Fail("Expected NullReferenceException but got none");
            }
            catch (NullReferenceException) {
                // this is what we expect
            }
            catch (Exception e) {
                Assert.Fail("Expected NullReferenceException but got: " + e.ToString());
            }
            // Deformatter with valid DeformatterAlgorithm property
            sig.KeyAlgorithm         = "DSA";
            sig.DigestAlgorithm      = "SHA1";
            sig.DeformatterAlgorithm = "DSASignatureDeformatter";
            try {
                def = sig.CreateDeformatter(dsa);
                Assert.Fail("Expected NullReferenceException but got none");
            }
            catch (NullReferenceException) {
                // this is what we expect
            }
            catch (Exception e) {
                Assert.Fail("Expected NullReferenceException but got: " + e.ToString());
            }
        }
예제 #2
0
        private static bool CheckSignedInfo(SignedXml signedXml, AsymmetricAlgorithm key)
        {
            //Copied from reflected System.Security.Cryptography.Xml.SignedXml
            SignatureDescription signatureDescription = CryptoConfig.CreateFromName(signedXml.SignatureMethod) as SignatureDescription;

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

            Type type  = Type.GetType(signatureDescription.KeyAlgorithm);
            Type type2 = key.GetType();

            if (type != type2 && !type.IsSubclassOf(type2) && !type2.IsSubclassOf(type))
            {
                return(false);
            }

            HashAlgorithm hashAlgorithm = signatureDescription.CreateDigest();

            if (hashAlgorithm == null)
            {
                throw new CryptographicException(SecurityResources.GetString("Cryptography_Xml_CreateHashAlgorithmFailed"));
            }

            //Except this. The SignedXml class creates and cananicalizes a Signature element without any prefix, rather than using the element from the document provided
            byte[] c14NDigest = GetC14NDigest(signedXml, hashAlgorithm);

            AsymmetricSignatureDeformatter asymmetricSignatureDeformatter = signatureDescription.CreateDeformatter(key);

            return(asymmetricSignatureDeformatter.VerifySignature(c14NDigest, signedXml.Signature.SignatureValue));
        }
예제 #3
0
        /// <summary>
        /// Valida la firma electronica utilizando una clave externa
        /// </summary>
        /// <param name="key">Clave publica asociada a la firma electrónica</param>
        /// <returns>true si la firma se valido correctamente</returns>
        public bool CheckSignature(AsymmetricAlgorithm key)
        {
            if (key == null)
            {
                throw new ArgumentNullException("key");
            }

            bool result = CheckReferenceIntegrity();

            if (result)
            {
                SignatureDescription sd = GetSignatureDescription(signature.SignedInfo.SignatureMethod);

                byte[] hash = Hash(sd.DigestAlgorithm);
                AsymmetricSignatureDeformatter verifier = sd.CreateDeformatter(key); //(AsymmetricSignatureDeformatter)CryptoConfig.CreateFromName(sd.DeformatterAlgorithm);
                if (verifier != null)
                {
                    //verifier.SetHashAlgorithm(sd.DigestAlgorithm);
                    //verifier.SetKey(key);
                    result = verifier.VerifySignature(hash, signature.SignatureValue);
                }
                else
                {
                    result = false;
                }
            }

            return(result);
        }
예제 #4
0
    public static Boolean Test()
    {
        Boolean bRes = true;

        SecurityElement el = new SecurityElement("whatever");
//		el.Text = "<Key>RSA</Key><Digest>SHA1</Digest><Formatter>System.Security.Cryptography.RSAPKCS1SignatureFormatter</Formatter><Deformatter>System.Security.Cryptography.RSAPKCS1SignatureFormatter</Deformatter>";
        SecurityElement el_key = new SecurityElement("Key");

        el_key.Text = "RSA";
        SecurityElement el_digest = new SecurityElement("Digest");

        el_digest.Text = "SHA1";
        SecurityElement el_form = new SecurityElement("Formatter");

        el_form.Text = "System.Security.Cryptography.RSAPKCS1SignatureFormatter";
        SecurityElement el_deform = new SecurityElement("Deformatter");

        el_deform.Text = "System.Security.Cryptography.RSAPKCS1SignatureDeformatter";

        el.AddChild(el_key);
        el.AddChild(el_digest);
        el.AddChild(el_form);
        el.AddChild(el_deform);

        SignatureDescription sd_empty = new SignatureDescription();

        SignatureDescription sd = new SignatureDescription(el);

        Console.WriteLine(sd.CreateDigest());
        Console.WriteLine(sd.CreateFormatter(RSA.Create()));
        Console.WriteLine(sd.CreateDeformatter(RSA.Create()));

        return(bRes);
    }
예제 #5
0
    public static Boolean Test()
    {
        Boolean bRes = true;

		SecurityElement el = new SecurityElement("whatever");
//		el.Text = "<Key>RSA</Key><Digest>SHA1</Digest><Formatter>System.Security.Cryptography.RSAPKCS1SignatureFormatter</Formatter><Deformatter>System.Security.Cryptography.RSAPKCS1SignatureFormatter</Deformatter>";
		SecurityElement el_key = new SecurityElement("Key");
		el_key.Text = "RSA";
		SecurityElement el_digest = new SecurityElement("Digest");
		el_digest.Text = "SHA1";
		SecurityElement el_form = new SecurityElement("Formatter");
		el_form.Text = "System.Security.Cryptography.RSAPKCS1SignatureFormatter";
		SecurityElement el_deform = new SecurityElement("Deformatter");
		el_deform.Text = "System.Security.Cryptography.RSAPKCS1SignatureDeformatter";

		el.AddChild(el_key);
		el.AddChild(el_digest);
		el.AddChild(el_form);
		el.AddChild(el_deform);

		SignatureDescription sd_empty = new SignatureDescription();
		
		SignatureDescription sd = new SignatureDescription(el);

		Console.WriteLine(sd.CreateDigest());
		Console.WriteLine(sd.CreateFormatter(RSA.Create()));
		Console.WriteLine(sd.CreateDeformatter(RSA.Create()));

        return bRes;
    }
        private bool CheckSignedInfo(AsymmetricAlgorithm key)
        {
            if (key == null)
            {
                throw new ArgumentNullException("key");
            }
            SignedXmlDebugLog.LogBeginCheckSignedInfo(this, this.m_signature.SignedInfo);
            SignatureDescription signatureDescription = CryptoConfig.CreateFromName(this.SignatureMethod) as SignatureDescription;

            if (signatureDescription == null)
            {
                throw new CryptographicException(SecurityResources.GetResourceString("Cryptography_Xml_SignatureDescriptionNotCreated"));
            }
            Type c    = Type.GetType(signatureDescription.KeyAlgorithm);
            Type type = key.GetType();

            if (((c != type) && !c.IsSubclassOf(type)) && !type.IsSubclassOf(c))
            {
                return(false);
            }
            HashAlgorithm hash = signatureDescription.CreateDigest();

            if (hash == null)
            {
                throw new CryptographicException(SecurityResources.GetResourceString("Cryptography_Xml_CreateHashAlgorithmFailed"));
            }
            byte[] actualHashValue = this.GetC14NDigest(hash);
            AsymmetricSignatureDeformatter asymmetricSignatureDeformatter = signatureDescription.CreateDeformatter(key);

            SignedXmlDebugLog.LogVerifySignedInfo(this, key, signatureDescription, hash, asymmetricSignatureDeformatter, actualHashValue, this.m_signature.SignatureValue);
            return(asymmetricSignatureDeformatter.VerifySignature(actualHashValue, this.m_signature.SignatureValue));
        }
        public override AsymmetricSignatureDeformatter GetSignatureDeformatter(string algorithm)
        {
            if (string.IsNullOrEmpty(algorithm))
            {
                throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgument(algorithm, System.IdentityModel.SR.GetString("EmptyOrNullArgumentString", new object[] { "algorithm" }));
            }
            object algorithmFromConfig = CryptoHelper.GetAlgorithmFromConfig(algorithm);

            if (algorithmFromConfig != null)
            {
                SignatureDescription description = algorithmFromConfig as SignatureDescription;
                if (description != null)
                {
                    return(description.CreateDeformatter(this.PublicKey.Key));
                }
                try
                {
                    AsymmetricSignatureDeformatter deformatter = algorithmFromConfig as AsymmetricSignatureDeformatter;
                    if (deformatter != null)
                    {
                        deformatter.SetKey(this.PublicKey.Key);
                        return(deformatter);
                    }
                }
                catch (InvalidCastException exception)
                {
                    throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new NotSupportedException(System.IdentityModel.SR.GetString("AlgorithmAndPublicKeyMisMatch"), exception));
                }
                throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new CryptographicException(System.IdentityModel.SR.GetString("UnsupportedAlgorithmForCryptoOperation", new object[] { algorithm, "GetSignatureDeformatter" })));
            }
            switch (algorithm)
            {
            case "http://www.w3.org/2000/09/xmldsig#dsa-sha1":
            {
                DSA key = this.PublicKey.Key as DSA;
                if (key == null)
                {
                    throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new NotSupportedException(System.IdentityModel.SR.GetString("PublicKeyNotDSA")));
                }
                return(new DSASignatureDeformatter(key));
            }

            case "http://www.w3.org/2000/09/xmldsig#rsa-sha1":
            case "http://www.w3.org/2001/04/xmldsig-more#rsa-sha256":
            {
                RSA rsa = this.PublicKey.Key as RSA;
                if (rsa == null)
                {
                    throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new NotSupportedException(System.IdentityModel.SR.GetString("PublicKeyNotRSA")));
                }
                return(new RSAPKCS1SignatureDeformatter(rsa));
            }
            }
            throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new NotSupportedException(System.IdentityModel.SR.GetString("UnsupportedCryptoAlgorithm", new object[] { algorithm })));
        }
예제 #8
0
        // Create a signature deformatter for DSA decryption.
        public static AsymmetricSignatureDeformatter CreateDSADeformatter(DSA dsa)
        {
            // Create a DSA signature deformatter to verify the signature.
            SignatureDescription signatureDescription = new SignatureDescription();

            signatureDescription.DeformatterAlgorithm = "System.Security.Cryptography.DSASignatureDeformatter";

            AsymmetricSignatureDeformatter asymmetricDeformatter = signatureDescription.CreateDeformatter(dsa);

            Console.WriteLine("\nCreated deformatter : " + asymmetricDeformatter.ToString());
            return(asymmetricDeformatter);
        }
예제 #9
0
        /// <summary>Gets the de-formatter algorithm for the digital signature.</summary>
        /// <param name="algorithm">The de-formatter algorithm for the digital signature to get an instance of.</param>
        /// <returns>An <see cref="T:System.Security.Cryptography.AsymmetricSignatureDeformatter" /> that represents the de-formatter algorithm for the digital signature.</returns>
        /// <exception cref="T:System.NotSupportedException">
        /// <paramref name="algorithm" /> is <see cref="F:System.Security.Cryptography.Xml.SignedXml.XmlDsigDSAUrl" /> and the public key for the X.509 certificate specified in the constructor is not of type <see cref="T:System.Security.Cryptography.DSA" />.-or-
        /// <paramref name="algorithm" /> is <see cref="F:System.Security.Cryptography.Xml.SignedXml.XmlDsigRSASHA1Url" /> or <see cref="F:System.IdentityModel.Tokens.SecurityAlgorithms.RsaSha256Signature" /> and the public key for the X.509 certificate specified in the constructor is not of type <see cref="T:System.Security.Cryptography.RSA" />.-or-
        /// <paramref name="algorithm" /> is not supported. The supported algorithms are <see cref="F:System.Security.Cryptography.Xml.SignedXml.XmlDsigDSAUrl" />,
        /// <see cref="F:System.Security.Cryptography.Xml.SignedXml.XmlDsigRSASHA1Url" />, and <see cref="F:System.IdentityModel.Tokens.SecurityAlgorithms.RsaSha256Signature" />.</exception>
        public override AsymmetricSignatureDeformatter GetSignatureDeformatter(
            string algorithm)
        {
            if (string.IsNullOrEmpty(algorithm))
            {
                throw new ArgumentNullException(nameof(algorithm));
            }

            object algorithmFromConfig = CryptoHelper.GetAlgorithmFromConfig(algorithm);

            if (algorithmFromConfig != null)
            {
                SignatureDescription signatureDescription = algorithmFromConfig as SignatureDescription;
                if (signatureDescription != null)
                {
                    return(signatureDescription.CreateDeformatter(this.PublicKey));
                }
                try
                {
                    AsymmetricSignatureDeformatter signatureDeformatter = algorithmFromConfig as AsymmetricSignatureDeformatter;
                    if (signatureDeformatter != null)
                    {
                        signatureDeformatter.SetKey(this.PublicKey);
                        return(signatureDeformatter);
                    }
                }
                catch (InvalidCastException ex) { throw new NotSupportedException("AlgorithmAndPublicKeyMisMatch", (Exception)ex); }

                throw new CryptographicException("UnsupportedAlgorithmForCryptoOperation");
            }
            if (algorithm != "http://www.w3.org/2000/09/xmldsig#dsa-sha1")
            {
                if (algorithm == "http://www.w3.org/2000/09/xmldsig#rsa-sha1" || algorithm == "http://www.w3.org/2001/04/xmldsig-more#rsa-sha256")
                {
                    RSA publicKey = this.PublicKey as RSA;
                    if (publicKey == null)
                    {
                        throw new NotSupportedException("PublicKeyNotRSA");
                    }

                    return((AsymmetricSignatureDeformatter) new ADSD.Crypto.RSAPKCS1SignatureDeformatter((AsymmetricAlgorithm)publicKey));
                }
                throw new NotSupportedException("UnsupportedCryptoAlgorithm");
            }
            DSA publicKey1 = this.PublicKey as DSA;

            if (publicKey1 == null)
            {
                throw new NotSupportedException("PublicKeyNotDSA");
            }

            return((AsymmetricSignatureDeformatter) new DSASignatureDeformatter((AsymmetricAlgorithm)publicKey1));
        }
        public void Deformatter()
        {
            AsymmetricSignatureDeformatter def;
            SignatureDescription           sig = new SignatureDescription();
            DSA dsa = DSA.Create();

            // Deformatter with all properties null
            AssertExtensions.Throws <ArgumentNullException>("name", () => sig.CreateDeformatter(dsa));

            // Deformatter with invalid DeformatterAlgorithm property
            sig.DeformatterAlgorithm = "DSA";
            Assert.ThrowsAny <Exception>(() => def = sig.CreateDeformatter(dsa));

            // Deformatter with valid DeformatterAlgorithm property
            sig.DeformatterAlgorithm = "DSASignatureDeformatter";
            Assert.Throws <NullReferenceException>(() => def = sig.CreateDeformatter(dsa));

            // Deformatter with valid DeformatterAlgorithm property
            sig.KeyAlgorithm         = "DSA";
            sig.DigestAlgorithm      = "SHA1";
            sig.DeformatterAlgorithm = "DSASignatureDeformatter";
            Assert.Throws <NullReferenceException>(() => def = sig.CreateDeformatter(dsa));
        }
예제 #11
0
        public override AsymmetricSignatureDeformatter GetSignatureDeformatter(string algorithm)
        {
            if (string.IsNullOrEmpty(algorithm))
            {
                throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgument(algorithm, SR.Format(SR.EmptyOrNullArgumentString, algorithm));
            }

            object algorithmObject = CryptoHelper.GetAlgorithmFromConfig(algorithm);

            if (algorithmObject != null)
            {
                SignatureDescription description = algorithmObject as SignatureDescription;
                if (description != null)
                {
                    return(description.CreateDeformatter(this.rsa));
                }

                try
                {
                    AsymmetricSignatureDeformatter asymmetricSignatureDeformatter = algorithmObject as AsymmetricSignatureDeformatter;
                    if (asymmetricSignatureDeformatter != null)
                    {
                        asymmetricSignatureDeformatter.SetKey(this.rsa);
                        return(asymmetricSignatureDeformatter);
                    }
                }
                catch (InvalidCastException e)
                {
                    throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new NotSupportedException(SR.Format(SR.AlgorithmAndKeyMisMatch, algorithm), e));
                }

                throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new CryptographicException(SR.Format(SR.UnsupportedAlgorithmForCryptoOperation,
                                                                                                               algorithm, "GetSignatureDeformatter")));
            }

            switch (algorithm)
            {
            case SecurityAlgorithms.RsaSha1Signature:
            case SecurityAlgorithms.RsaSha256Signature:
                return(new RSAPKCS1SignatureDeformatter(rsa));

            default:
                throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new CryptographicException(SR.Format(SR.UnsupportedAlgorithmForCryptoOperation,
                                                                                                               algorithm, "GetSignatureDeformatter")));
            }
        }
예제 #12
0
        private bool CheckSignedInfo(AsymmetricAlgorithm key)
        {
            if (key == null)
            {
                throw new ArgumentNullException("key");
            }

            SignedXmlDebugLog.LogBeginCheckSignedInfo(this, m_signature.SignedInfo);

            SignatureDescription signatureDescription = CryptoConfig.CreateFromName(SignatureMethod) as SignatureDescription;

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

            // Let's see if the key corresponds with the SignatureMethod
            Type ta = Type.GetType(signatureDescription.KeyAlgorithm);
            Type tb = key.GetType();

            if ((ta != tb) && !ta.IsSubclassOf(tb) && !tb.IsSubclassOf(ta))
            {
                // Signature method key mismatch
                return(false);
            }

            HashAlgorithm hashAlgorithm = signatureDescription.CreateDigest();

            if (hashAlgorithm == null)
            {
                throw new CryptographicException(SecurityResources.GetResourceString("Cryptography_Xml_CreateHashAlgorithmFailed"));
            }
            byte[] hashval = GetC14NDigest(hashAlgorithm);

            AsymmetricSignatureDeformatter asymmetricSignatureDeformatter = signatureDescription.CreateDeformatter(key);

            SignedXmlDebugLog.LogVerifySignedInfo(this,
                                                  key,
                                                  signatureDescription,
                                                  hashAlgorithm,
                                                  asymmetricSignatureDeformatter,
                                                  hashval,
                                                  m_signature.SignatureValue);
            return(asymmetricSignatureDeformatter.VerifySignature(hashval, m_signature.SignatureValue));
        }
예제 #13
0
        private bool CheckSignedInfo(AsymmetricAlgorithm key)
        {
            if (key == null)
            {
                throw new ArgumentNullException(nameof(key));
            }

            SignedXmlDebugLog.LogBeginCheckSignedInfo(this, m_signature.SignedInfo);

            SignatureDescription signatureDescription = CryptoConfig.CreateFromName(SignatureMethod) as SignatureDescription;

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

            // Let's see if the key corresponds with the SignatureMethod
            Type ta = Type.GetType(signatureDescription.KeyAlgorithm);

            if (!IsKeyTheCorrectAlgorithm(key, ta))
            {
                return(false);
            }

            HashAlgorithm hashAlgorithm = signatureDescription.CreateDigest();

            if (hashAlgorithm == null)
            {
                throw new CryptographicException(SR.Cryptography_Xml_CreateHashAlgorithmFailed);
            }
            byte[] hashval = GetC14NDigest(hashAlgorithm);

            AsymmetricSignatureDeformatter asymmetricSignatureDeformatter = signatureDescription.CreateDeformatter(key);

            SignedXmlDebugLog.LogVerifySignedInfo(this,
                                                  key,
                                                  signatureDescription,
                                                  hashAlgorithm,
                                                  asymmetricSignatureDeformatter,
                                                  hashval,
                                                  m_signature.SignatureValue);
            return(asymmetricSignatureDeformatter.VerifySignature(hashval, m_signature.SignatureValue));
        }
        void RSASignatureDescriptionCore(string name, string expectedDigestAlgorithm, string expectedSelectedDigestAlgorithm)
        {
            // internal class - we cannot create one without CryptoConfig
            SignatureDescription sd = (SignatureDescription)CryptoConfig.CreateFromName(name);

            Assert.AreEqual(expectedDigestAlgorithm, sd.DigestAlgorithm);
            Assert.AreEqual("System.Security.Cryptography.RSAPKCS1SignatureDeformatter", sd.DeformatterAlgorithm);
            Assert.AreEqual("System.Security.Cryptography.RSAPKCS1SignatureFormatter", sd.FormatterAlgorithm);
            Assert.AreEqual("System.Security.Cryptography.RSA", sd.KeyAlgorithm);

            HashAlgorithm hash = sd.CreateDigest();

            Assert.AreEqual(expectedSelectedDigestAlgorithm, hash.ToString());

            Assert.AreEqual("System.Security.Cryptography.RSA", sd.KeyAlgorithm);

            AsymmetricSignatureDeformatter asd = sd.CreateDeformatter(rsa);

            Assert.AreEqual("System.Security.Cryptography.RSAPKCS1SignatureDeformatter", asd.ToString());

            AsymmetricSignatureFormatter asf = sd.CreateFormatter(rsa);

            Assert.AreEqual("System.Security.Cryptography.RSAPKCS1SignatureFormatter", asf.ToString());
        }
        public void DSASignatureDescription()
        {
            // internal class - we cannot create one without CryptoConfig
            SignatureDescription sd = (SignatureDescription)CryptoConfig.CreateFromName("http://www.w3.org/2000/09/xmldsig#dsa-sha1");

            Assert.AreEqual("System.Security.Cryptography.SHA1CryptoServiceProvider", sd.DigestAlgorithm);
            Assert.AreEqual("System.Security.Cryptography.DSASignatureDeformatter", sd.DeformatterAlgorithm);
            Assert.AreEqual("System.Security.Cryptography.DSASignatureFormatter", sd.FormatterAlgorithm);
            Assert.AreEqual("System.Security.Cryptography.DSACryptoServiceProvider", sd.KeyAlgorithm);

            HashAlgorithm hash = sd.CreateDigest();

            Assert.AreEqual("System.Security.Cryptography.SHA1CryptoServiceProvider", hash.ToString());

            Assert.AreEqual(dsa.ToString(), sd.KeyAlgorithm);

            AsymmetricSignatureDeformatter asd = sd.CreateDeformatter(dsa);

            Assert.AreEqual("System.Security.Cryptography.DSASignatureDeformatter", asd.ToString());

            AsymmetricSignatureFormatter asf = sd.CreateFormatter(dsa);

            Assert.AreEqual("System.Security.Cryptography.DSASignatureFormatter", asf.ToString());
        }
예제 #16
0
        public void Deformatter()
        {
            AsymmetricSignatureDeformatter def;
            SignatureDescription sig = new SignatureDescription();
            DSA dsa = DSA.Create();

            // Deformatter with all properties null
            Assert.Throws<ArgumentNullException>("name", () => sig.CreateDeformatter(dsa));

            // Deformatter with invalid DeformatterAlgorithm property
            sig.DeformatterAlgorithm = "DSA";
            Assert.ThrowsAny<Exception>(() => def = sig.CreateDeformatter(dsa));

            // Deformatter with valid DeformatterAlgorithm property
            sig.DeformatterAlgorithm = "DSASignatureDeformatter";
            Assert.Throws<NullReferenceException>(() => def = sig.CreateDeformatter(dsa));

            // Deformatter with valid DeformatterAlgorithm property
            sig.KeyAlgorithm = "DSA";
            sig.DigestAlgorithm = "SHA1";
            sig.DeformatterAlgorithm = "DSASignatureDeformatter";
            Assert.Throws<NullReferenceException>(() => def = sig.CreateDeformatter(dsa));
        }
예제 #17
0
        public override AsymmetricSignatureDeformatter GetSignatureDeformatter(string algorithm)
        {
            // We support one of the two algoritms, but not both.
            //     XmlDsigDSAUrl = "http://www.w3.org/2000/09/xmldsig#dsa-sha1";
            //     XmlDsigRSASHA1Url = "http://www.w3.org/2000/09/xmldsig#rsa-sha1";

            if (string.IsNullOrEmpty(algorithm))
            {
                throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgument(algorithm, SR.GetString(SR.EmptyOrNullArgumentString, "algorithm"));
            }

            object algorithmObject = CryptoHelper.GetAlgorithmFromConfig(algorithm);

            if (algorithmObject != null)
            {
                SignatureDescription description = algorithmObject as SignatureDescription;
                if (description != null)
                {
                    return(description.CreateDeformatter(this.PublicKey));
                }

                try
                {
                    AsymmetricSignatureDeformatter asymmetricSignatureDeformatter = algorithmObject as AsymmetricSignatureDeformatter;
                    if (asymmetricSignatureDeformatter != null)
                    {
                        asymmetricSignatureDeformatter.SetKey(this.PublicKey);
                        return(asymmetricSignatureDeformatter);
                    }
                }
                catch (InvalidCastException e)
                {
                    throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new NotSupportedException(SR.GetString(SR.AlgorithmAndPublicKeyMisMatch), e));
                }

                throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new CryptographicException(SR.GetString(SR.UnsupportedAlgorithmForCryptoOperation,
                                                                                                                  algorithm, "GetSignatureDeformatter")));
            }

            switch (algorithm)
            {
            case SignedXml.XmlDsigDSAUrl:

                // Ensure that we have a DSA algorithm object.
                DSA dsa = (this.PublicKey as DSA);
                if (dsa == null)
                {
                    throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new NotSupportedException(SR.GetString(SR.PublicKeyNotDSA)));
                }
                return(new DSASignatureDeformatter(dsa));

            case SignedXml.XmlDsigRSASHA1Url:
            case SecurityAlgorithms.RsaSha256Signature:
                // Ensure that we have an RSA algorithm object.
                RSA rsa = (this.PublicKey as RSA);
                if (rsa == null)
                {
                    throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new NotSupportedException(SR.GetString(SR.PublicKeyNotRSA)));
                }
                return(new RSAPKCS1SignatureDeformatter(rsa));

            default:
                throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new NotSupportedException(SR.GetString(SR.UnsupportedCryptoAlgorithm, algorithm)));
            }
        }
예제 #18
0
        /// <include file='doc\SignedXml.uex' path='docs/doc[@for="SignedXml.CheckSignature1"]/*' />
        public bool CheckSignature(AsymmetricAlgorithm key)
        {
            if (key == null)
            {
                throw new ArgumentNullException("key");
            }

            SignatureDescription signatureDescription = (SignatureDescription)CryptoConfig.CreateFromName(m_signature.SignedInfo.SignatureMethod);

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

            // Let's see if the key corresponds with the SignatureMethod
            Type ta = Type.GetType(signatureDescription.KeyAlgorithm);
            Type tb = key.GetType();

            if ((ta != tb) && !ta.IsSubclassOf(tb) && !tb.IsSubclassOf(ta))
            {
                // Signature method key mismatch
                return(false);
            }

            // set up the canonicalizer & canonicalize SignedInfo
            TransformChain tc = new TransformChain();
            Transform      c14nMethodTransform = (Transform)CryptoConfig.CreateFromName(SignedInfo.CanonicalizationMethod);

            if (c14nMethodTransform == null)
            {
                throw new CryptographicException(String.Format(SecurityResources.GetResourceString("Cryptography_Xml_CreateTransformFailed"), SignedInfo.CanonicalizationMethod));
            }
            tc.Add(c14nMethodTransform);
            XmlElement signedInfo = SignedInfo.GetXml().Clone() as XmlElement;

            // Add non default namespaces in scope
            if (m_namespaces != null)
            {
                foreach (XmlNode attrib in m_namespaces)
                {
                    string name = ((attrib.Prefix != String.Empty) ? attrib.Prefix + ":" + attrib.LocalName : attrib.LocalName);
                    // Skip the attribute if one with the same qualified name already exists
                    if (signedInfo.HasAttribute(name) || (name.Equals("xmlns") && signedInfo.NamespaceURI != String.Empty))
                    {
                        continue;
                    }
                    XmlAttribute nsattrib = m_containingDocument.CreateAttribute(name);
                    nsattrib.Value = ((XmlNode)attrib).Value;
                    signedInfo.SetAttributeNode(nsattrib);
                }
            }
            string      strBaseUri             = (m_containingDocument == null ? null : m_containingDocument.BaseURI);
            XmlResolver resolver               = (m_bResolverSet ? m_xmlResolver : new XmlSecureResolver(new XmlUrlResolver(), strBaseUri));
            Stream      canonicalizedSignedXml = tc.TransformToOctetStream(PreProcessElementInput(signedInfo, resolver, strBaseUri), resolver, strBaseUri);

            // calculate the hash
            HashAlgorithm hashAlgorithm = signatureDescription.CreateDigest();

            if (hashAlgorithm == null)
            {
                throw new CryptographicException(SecurityResources.GetResourceString("Cryptography_Xml_CreateHashAlgorithmFailed"));
            }
            byte[] hashval = hashAlgorithm.ComputeHash(canonicalizedSignedXml);

            // We can FINALLY generate the SignatureValue
#if _DEBUG
            if (debug)
            {
                Console.WriteLine("Computed canonicalized SignedInfo:");
                Console.WriteLine(signedInfo.OuterXml);
                Console.WriteLine("Computed Hash:");
                Console.WriteLine(Convert.ToBase64String(hashval));
                Console.WriteLine("m_signature.SignatureValue:");
                Console.WriteLine(Convert.ToBase64String(m_signature.SignatureValue));
            }
#endif
            AsymmetricSignatureDeformatter asymmetricSignatureDeformatter = signatureDescription.CreateDeformatter(key);
            bool bRet = asymmetricSignatureDeformatter.VerifySignature(hashAlgorithm, m_signature.SignatureValue);

            if (bRet != true)
            {
#if _DEBUG
                if (debug)
                {
                    Console.WriteLine("Failed to verify the signature on SignedInfo.");
                }
#endif
                return(false);
            }

            // Now is the time to go through all the references and see if their
            // DigestValue are good
            return(CheckDigestedReferences());
        }
예제 #19
0
 public AsymmetricSignatureDeformatter CreateDeformatter()
 {
     return(SignatureDescription.CreateDeformatter(Certificate.GetRSAPublicKey()));
 }