private static void VerifySignatureWithHashAlgorithm(AsymmetricSignatureFormatter formatter, AsymmetricSignatureDeformatter deformatter, HashAlgorithm hashAlgorithm)
        {
            byte[] signature = formatter.CreateSignature(hashAlgorithm);
            Assert.True(deformatter.VerifySignature(hashAlgorithm, signature));

            signature[signature.Length - 1] ^= 0xff;
            Assert.False(deformatter.VerifySignature(hashAlgorithm, signature));
        }
示例#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));
        }
        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));
        }
示例#4
0
        /// <summary>
        /// Verifies that a signature over the' input' matches the signature.
        /// </summary>
        /// <param name="input">the bytes to generate the signature over.</param>
        /// <param name="signature">the value to verify against.</param>
        /// <returns>true if signature matches, false otherwise.</returns>
        /// <exception cref="T:System.ArgumentNullException">'input' is null.</exception>
        /// <exception cref="T:System.ArgumentNullException">'signature' is null.</exception>
        /// <exception cref="T:System.ArgumentException">'input.Length' == 0.</exception>
        /// <exception cref="T:System.ArgumentException">'signature.Length' == 0.</exception>
        /// <exception cref="T:System.ObjectDisposedException">if <see cref="M:System.IdentityModel.Tokens.AsymmetricSignatureProvider.Dispose(System.Boolean)" /> has been called. </exception>
        /// <exception cref="T:System.InvalidOperationException">if the internal <see cref="T:System.Security.Cryptography.AsymmetricSignatureDeformatter" /> is null. This can occur if a derived type does not call the base constructor.</exception>
        /// <exception cref="T:System.InvalidOperationException">if the internal <see cref="T:System.Security.Cryptography.HashAlgorithm" /> is null. This can occur if a derived type deletes it or does not create it.</exception>
        public override bool Verify(byte[] input, byte[] signature)
        {
            if (input == null)
            {
                throw new ArgumentNullException(nameof(input));
            }
            if (signature == null)
            {
                throw new ArgumentNullException(nameof(signature));
            }
            if (input.Length == 0)
            {
                throw new ArgumentException("IDX10625: Cannot verify signature 'input' byte array has length 0.");
            }
            if (signature.Length == 0)
            {
                throw new ArgumentException("IDX10626: Cannot verify signature 'signature' byte array has length 0.");
            }
            if (disposed)
            {
                throw new ObjectDisposedException(GetType().ToString());
            }
            if (deformatter == null)
            {
                throw new InvalidOperationException("IDX10629: The AsymmetricSignatureDeformatter is null, cannot sign data. If a derived AsymmetricSignatureProvider is being used, make sure to call the base constructor.");
            }
            if (hash == null)
            {
                throw new InvalidOperationException("IDX10621: This AsymmetricSignatureProvider has a minimum key size requirement of: '{0}', the AsymmetricSecurityKey in has a KeySize of: '{1}'.");
            }

            return(deformatter.VerifySignature(hash.ComputeHash(input), signature));
        }
示例#5
0
        public void RSAPKCS1SHA256RoundTripTest()
        {
            using (RSACryptoServiceProvider rsa = new RSACryptoServiceProvider(2048))
            {
                RSAPKCS1SHA256SignatureDescription sd = new RSAPKCS1SHA256SignatureDescription();

                using (HashAlgorithm digestAlgorithm = sd.CreateDigest())
                {
                    // Create some data to sign
                    RNGCryptoServiceProvider rng = new RNGCryptoServiceProvider();
                    byte[] data = new byte[1025];
                    rng.GetBytes(data);
                    byte[] hash = digestAlgorithm.ComputeHash(data);

                    // Sign the data
                    AsymmetricSignatureFormatter formatter = sd.CreateFormatter(rsa);
                    byte[] signature = formatter.CreateSignature(hash);
                    Assert.IsNotNull(signature, "Failed to create a signature");

                    // Verify the signature
                    AsymmetricSignatureDeformatter deformatter = sd.CreateDeformatter(rsa);
                    Assert.IsTrue(deformatter.VerifySignature(hash, signature), "Failed to verify signature");
                }
            }
        }
示例#6
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);
        }
示例#7
0
        private void VerifySignature(HashAlgorithm hash, AsymmetricSignatureDeformatter deformatter, string signatureMethod)
        {
            bool flag;

            this.Signature.SignedInfo.ComputeHash(hash);
            if (System.IdentityModel.SecurityUtils.RequiresFipsCompliance && (signatureMethod == "http://www.w3.org/2001/04/xmldsig-more#rsa-sha256"))
            {
                deformatter.SetHashAlgorithm("SHA256");
                flag = deformatter.VerifySignature(hash.Hash, this.GetSignatureValue());
            }
            else
            {
                flag = deformatter.VerifySignature(hash, this.GetSignatureValue());
            }
            if (!flag)
            {
                throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new CryptographicException(System.IdentityModel.SR.GetString("SignatureVerificationFailed")));
            }
        }
示例#8
0
        public bool VerifySign(string data, string sign)
        {
            HashAlgorithm ha = (HashAlgorithm) new SHA1CryptoServiceProvider();

            ha.Initialize();
            byte[] buf  = Convert.FromBase64String(sign);
            byte[] hash = ha.ComputeHash(_encoding.GetBytes(data));
            AsymmetricSignatureDeformatter df =
                (AsymmetricSignatureDeformatter) new RSAPKCS1SignatureDeformatter(rsaCryptoServiceProvider);

            df.SetHashAlgorithm(HashAlgorithmName);
            return(df.VerifySignature(hash, buf));
        }
示例#9
0
        public void VerifySignature(string providedSignature)
        {
            this.SetSignatureValue(providedSignature);

            AsymmetricAlgorithm  privateKey;
            SignatureDescription description;
            HashAlgorithm        hash;

            this.ComputeHash(out privateKey, out description, out hash);

            AsymmetricSignatureDeformatter deformatter = description.CreateDeformatter(privateKey);

            if (!deformatter.VerifySignature(hash, this.signatureValue))
            {
                throw new CompactSignatureSecurityException("Signature verification failed");
            }
        }
示例#10
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));
        }
示例#11
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));
        }
示例#12
0
        private static bool ValidateSignature(string data, string signature)
        {
            bool result;

            var dataBytes = Encoding.UTF8.GetBytes(data);
            var dataHash  = _hashAlgorithm.ComputeHash(dataBytes);

            try
            {
                var signatureBytes = Convert.FromBase64String(signature);
                result = _signatureDeformatter.VerifySignature(dataHash, signatureBytes);
            }
            catch (FormatException)
            {
                result = false;
            }

            return(result);
        }
        // Is the signature (over SignedInfo) valid ?
        private bool CheckSignatureWithKey(AsymmetricAlgorithm key)
        {
            if (key == null)
            {
                return(false);
            }

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

            if (sd == null)
            {
                return(false);
            }

            AsymmetricSignatureDeformatter verifier = (AsymmetricSignatureDeformatter)CryptoConfig.CreateFromName(sd.DeformatterAlgorithm);

            if (verifier == null)
            {
                return(false);
            }

            try
            {
                verifier.SetKey(key);
                verifier.SetHashAlgorithm(sd.DigestAlgorithm);

                HashAlgorithm hash = GetHash(sd.DigestAlgorithm, true);
                // get the hash of the C14N SignedInfo element
                MemoryStream ms = (MemoryStream)SignedInfoTransformed();

                byte[] digest = hash.ComputeHash(ms);
                return(verifier.VerifySignature(digest, m_signature.SignatureValue));
            }
            catch
            {
                // e.g. SignatureMethod != AsymmetricAlgorithm type
                return(false);
            }
        }
 protected static void InvalidDeformatterArguments(AsymmetricSignatureDeformatter deformatter)
 {
     Assert.Throws<ArgumentNullException>(() => deformatter.SetKey(null));
     Assert.Throws<ArgumentNullException>(() => deformatter.VerifySignature((byte[])null, new byte[] { 0, 1, 2 }));
     Assert.Throws<CryptographicUnexpectedOperationException>(() => deformatter.VerifySignature(new byte[] { 0, 1, 2 }, new byte[] { 0, 1, 2 }));
 }
        // Format:
        //   SignatureLength : 4-byte big-endian integer
        //   Signature       : Octet stream, length is SignatureLength
        //   CookieValue     : Octet stream, remainder of message

        /// <summary>
        /// Verifies the signature.  All keys in the collection VerificationKeys will be attempted.
        /// </summary>
        /// <param name="encoded">Data previously returned from <see cref="Encode"/></param>
        /// <returns>The originally signed data.</returns>
        /// <exception cref="ArgumentNullException">The argument 'encoded' is null.</exception>
        /// <exception cref="ArgumentException">The argument 'encoded' contains zero bytes.</exception>
        /// <exception cref="FormatException">The data is in the wrong format.</exception>
        /// <exception cref="CryptographicException">The signature is invalid.</exception>
        /// <exception cref="NotSupportedException">The platform does not support the requested algorithm.</exception>
        /// <exception cref="InvalidOperationException">There are no verification keys.</exception>
        public override byte[] Decode(byte[] encoded)
        {
            if (null == encoded)
            {
                throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("encoded");
            }

            if (0 == encoded.Length)
            {
                throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgument("encoded", SR.GetString(SR.ID6045));
            }

            ReadOnlyCollection <RSA> verificationKeys = VerificationKeys;

            if (0 == verificationKeys.Count)
            {
                throw DiagnosticUtility.ThrowHelperInvalidOperation(SR.GetString(SR.ID6036));
            }

            // Decode the message ...
            int currentIndex = 0;

            // SignatureLength : 4-byte big-endian integer
            if (encoded.Length < sizeof(Int32))
            {
                throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new FormatException(SR.GetString(SR.ID1012)));
            }
            Int32 signatureLength = BitConverter.ToInt32(encoded, currentIndex);

            if (signatureLength < 0)
            {
                throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new FormatException(SR.GetString(SR.ID1005, signatureLength)));
            }

            if (signatureLength >= encoded.Length - sizeof(Int32))
            {
                throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new FormatException(SR.GetString(SR.ID1013)));
            }
            currentIndex += sizeof(Int32);

            // Signature        : Octet stream, length is SignatureLength
            byte[] signature = new byte[signatureLength];
            Array.Copy(encoded, currentIndex, signature, 0, signature.Length);
            currentIndex += signature.Length;

            // CookieValue      : Octet stream, remainder of message
            byte[] cookieValue = new byte[encoded.Length - currentIndex];
            Array.Copy(encoded, currentIndex, cookieValue, 0, cookieValue.Length);

            bool verified = false;

            try
            {
                // Verify the signature
                using (HashAlgorithm hash = CryptoHelper.CreateHashAlgorithm(HashName))
                {
                    hash.ComputeHash(cookieValue);

                    foreach (RSA rsa in verificationKeys)
                    {
                        AsymmetricSignatureDeformatter verifier = GetSignatureDeformatter(rsa);
                        if ((isSha256() && CryptoHelper.VerifySignatureForSha256(verifier, hash, signature)) ||
                            verifier.VerifySignature(hash, signature))
                        {
                            verified = true;
                            break;
                        }
                    }
                }
            }

            // Not all algorithms are supported on all OS
            catch (CryptographicException e)
            {
                throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new NotSupportedException(SR.GetString(SR.ID6035, HashName, verificationKeys[0].GetType().FullName), e));
            }

            if (!verified)
            {
                throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new CryptographicException(SR.GetString(SR.ID1014)));
            }

            return(cookieValue);
        }
示例#16
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());
        }
 protected static void InvalidDeformatterArguments(AsymmetricSignatureDeformatter deformatter)
 {
     Assert.Throws <ArgumentNullException>(() => deformatter.SetKey(null));
     Assert.Throws <ArgumentNullException>(() => deformatter.VerifySignature((byte[])null, new byte[] { 0, 1, 2 }));
     Assert.Throws <CryptographicUnexpectedOperationException>(() => deformatter.VerifySignature(new byte[] { 0, 1, 2 }, new byte[] { 0, 1, 2 }));
 }
示例#18
0
 internal static bool VerifySignatureForSha256(AsymmetricSignatureDeformatter deformatter, HashAlgorithm hash, byte[] signatureValue)
 {
     return(deformatter.VerifySignature(hash, signatureValue));
 }