Esempio n. 1
0
        /// <include file='doc\KeyInfo.uex' path='docs/doc[@for="RSAKeyValue.LoadXml"]/*' />
        public override void LoadXml(XmlElement value)
        {
            // Guard against nulls
            if (value == null)
            {
                throw new ArgumentNullException("value");
            }
            // Get the inner RSAKeyValue node
            XmlNamespaceManager nsm = new XmlNamespaceManager(value.OwnerDocument.NameTable);

            nsm.AddNamespace("ds", SignedXml.XmlDsigNamespaceUrl);
            XmlNodeList rsaKeyValueNodes = value.SelectNodes("ds:RSAKeyValue", nsm);

            if (rsaKeyValueNodes.Count == 0)
            {
                throw new CryptographicException(SecurityResources.GetResourceString("Cryptography_Xml_InvalidElement"), "KeyValue");
            }
            XmlElement rsaKeyValueElement = (XmlElement)rsaKeyValueNodes.Item(0);
            // Get the XML string
            String rsaKeyValueString = rsaKeyValueElement.OuterXml;

            // import the params
            m_key.FromXmlString(rsaKeyValueString);
        }
 public void CopyTo(Array array, int index)
 {
     if (array == null)
     {
         throw new ArgumentNullException("array");
     }
     if (array.Rank != 1)
     {
         throw new ArgumentException(SecurityResources.GetResourceString("Arg_RankMultiDimNotSupported"));
     }
     if ((index < 0) || (index >= array.Length))
     {
         throw new ArgumentOutOfRangeException("index", SecurityResources.GetResourceString("ArgumentOutOfRange_Index"));
     }
     if ((index + this.Count) > array.Length)
     {
         throw new ArgumentException(SecurityResources.GetResourceString("Argument_InvalidOffLen"));
     }
     for (int i = 0; i < this.Count; i++)
     {
         array.SetValue(this[i], index);
         index++;
     }
 }
Esempio n. 3
0
        // decrypts the supplied wrapped key using the provided symmetric algorithm
        public static byte[] DecryptKey(byte[] keyData, SymmetricAlgorithm symmetricAlgorithm)
        {
            if (keyData == null)
            {
                throw new ArgumentNullException("keyData");
            }
            if (symmetricAlgorithm == null)
            {
                throw new ArgumentNullException("symmetricAlgorithm");
            }

            if (symmetricAlgorithm is TripleDES)
            {
                // CMS Triple DES Key Wrap
                return(SymmetricKeyWrap.TripleDESKeyWrapDecrypt(symmetricAlgorithm.Key, keyData));
            }
            else if (symmetricAlgorithm is Rijndael || symmetricAlgorithm is Aes)
            {
                // FIPS AES Key Wrap
                return(SymmetricKeyWrap.AESKeyWrapDecrypt(symmetricAlgorithm.Key, keyData));
            }
            // throw an exception if the transform is not in the previous categories
            throw new CryptographicException(SecurityResources.GetResourceString("Cryptography_Xml_NotSupportedCryptographicTransform"));
        }
Esempio n. 4
0
        /// <include file='doc\SignedXml.uex' path='docs/doc[@for="SignedXml.CheckSignature"]/*' />
        public bool CheckSignature()
        {
            // We are not checking if the signature is valid in regards of it's
            // DTD. We are checking the integrity of the referenced data and the
            // SignatureValue itself
            bool bRet = false;
            AsymmetricAlgorithm key;

            if (KeyInfo == null)
            {
                throw new CryptographicException(SecurityResources.GetResourceString("Cryptography_Xml_KeyInfoRequired"));
            }

            do
            {
                key = GetPublicKey();
                if (key != null)
                {
                    bRet = CheckSignature(key);
                }
            } while (key != null && bRet == false);

            return(bRet);
        }
Esempio n. 5
0
        /// <summary>
        ///     Log that signature verification is beginning
        /// </summary>
        /// <param name="signedXml">SignedXml object doing the verification</param>
        /// <param name="context">Context of the verification</param>
        internal static void LogBeginSignatureVerification(SignedXml signedXml, XmlElement context)
        {
            Debug.Assert(signedXml != null, "signedXml != null");

            if (InformationLoggingEnabled)
            {
                WriteLine(signedXml,
                          TraceEventType.Information,
                          SignedXmlDebugEvent.BeginSignatureVerification,
                          SecurityResources.GetResourceString("Log_BeginSignatureVerification"));
            }

            if (VerboseLoggingEnabled)
            {
                string contextData = String.Format(CultureInfo.InvariantCulture,
                                                   SecurityResources.GetResourceString("Log_XmlContext"),
                                                   context != null ? context.OuterXml : NullString);

                WriteLine(signedXml,
                          TraceEventType.Verbose,
                          SignedXmlDebugEvent.BeginSignatureVerification,
                          contextData);
            }
        }
Esempio n. 6
0
        public void DecryptDocument()
        {
            XmlNamespaceManager nsmgr = new XmlNamespaceManager(this.m_document.NameTable);

            nsmgr.AddNamespace("enc", "http://www.w3.org/2001/04/xmlenc#");
            XmlNodeList list = this.m_document.SelectNodes("//enc:EncryptedData", nsmgr);

            if (list != null)
            {
                foreach (XmlNode node in list)
                {
                    XmlElement    element       = node as XmlElement;
                    EncryptedData encryptedData = new EncryptedData();
                    encryptedData.LoadXml(element);
                    SymmetricAlgorithm decryptionKey = this.GetDecryptionKey(encryptedData, null);
                    if (decryptionKey == null)
                    {
                        throw new CryptographicException(SecurityResources.GetResourceString("Cryptography_Xml_MissingDecryptionKey"));
                    }
                    byte[] decryptedData = this.DecryptData(encryptedData, decryptionKey);
                    this.ReplaceData(element, decryptedData);
                }
            }
        }
Esempio n. 7
0
        /// <summary>
        ///     Log that an X509 chain is being built for a certificate
        /// </summary>
        /// <param name="signedXml">SignedXml object building the chain</param>
        /// <param name="chain">chain built for the certificate</param>
        /// <param name="certificate">certificate having the chain built for it</param>
        internal static void LogVerifyX509Chain(SignedXml signedXml, X509Chain chain, X509Certificate certificate)
        {
            Debug.Assert(signedXml != null, "signedXml != null");
            Debug.Assert(certificate != null, "certificate != null");
            Debug.Assert(chain != null, "chain != null");

            if (InformationLoggingEnabled)
            {
                string buildMessage = String.Format(CultureInfo.InvariantCulture,
                                                    SecurityResources.GetResourceString("Log_BuildX509Chain"),
                                                    GetKeyName(certificate));
                WriteLine(signedXml,
                          TraceEventType.Information,
                          SignedXmlDebugEvent.X509Verification,
                          buildMessage);
            }

            if (VerboseLoggingEnabled)
            {
                // Dump out the flags and other miscelanious information used for building
                string revocationMode = String.Format(CultureInfo.InvariantCulture,
                                                      SecurityResources.GetResourceString("Log_RevocationMode"),
                                                      chain.ChainPolicy.RevocationFlag);
                WriteLine(signedXml, TraceEventType.Verbose, SignedXmlDebugEvent.X509Verification, revocationMode);

                string revocationFlag = String.Format(CultureInfo.InvariantCulture,
                                                      SecurityResources.GetResourceString("Log_RevocationFlag"),
                                                      chain.ChainPolicy.RevocationFlag);
                WriteLine(signedXml, TraceEventType.Verbose, SignedXmlDebugEvent.X509Verification, revocationFlag);

                string verificationFlags = String.Format(CultureInfo.InvariantCulture,
                                                         SecurityResources.GetResourceString("Log_VerificationFlag"),
                                                         chain.ChainPolicy.VerificationFlags);
                WriteLine(signedXml, TraceEventType.Verbose, SignedXmlDebugEvent.X509Verification, verificationFlags);

                string verificationTime = String.Format(CultureInfo.InvariantCulture,
                                                        SecurityResources.GetResourceString("Log_VerificationTime"),
                                                        chain.ChainPolicy.VerificationTime);
                WriteLine(signedXml, TraceEventType.Verbose, SignedXmlDebugEvent.X509Verification, verificationTime);

                string urlTimeout = String.Format(CultureInfo.InvariantCulture,
                                                  SecurityResources.GetResourceString("Log_UrlTimeout"),
                                                  chain.ChainPolicy.UrlRetrievalTimeout);
                WriteLine(signedXml, TraceEventType.Verbose, SignedXmlDebugEvent.X509Verification, urlTimeout);
            }

            // If there were any errors in the chain, make sure to dump those out
            if (InformationLoggingEnabled)
            {
                foreach (X509ChainStatus status in chain.ChainStatus)
                {
                    if (status.Status != X509ChainStatusFlags.NoError)
                    {
                        string logMessage = String.Format(CultureInfo.InvariantCulture,
                                                          SecurityResources.GetResourceString("Log_X509ChainError"),
                                                          status.Status,
                                                          status.StatusInformation);

                        WriteLine(signedXml,
                                  TraceEventType.Information,
                                  SignedXmlDebugEvent.X509Verification,
                                  logMessage);
                    }
                }
            }

            // Finally, dump out the chain itself
            if (VerboseLoggingEnabled)
            {
                StringBuilder chainElements = new StringBuilder();
                chainElements.Append(SecurityResources.GetResourceString("Log_CertificateChain"));

                foreach (X509ChainElement element in chain.ChainElements)
                {
                    chainElements.AppendFormat(CultureInfo.InvariantCulture, " {0}", GetKeyName(element.Certificate));
                }

                WriteLine(signedXml,
                          TraceEventType.Verbose,
                          SignedXmlDebugEvent.X509Verification,
                          chainElements.ToString());
            }
        }
Esempio n. 8
0
        public override void LoadXml(XmlElement value)
        {
            if (value == null)
            {
                throw new ArgumentNullException("value");
            }

            XmlNamespaceManager nsm = new XmlNamespaceManager(value.OwnerDocument.NameTable);

            nsm.AddNamespace("enc", EncryptedXml.XmlEncNamespaceUrl);
            nsm.AddNamespace("ds", SignedXml.XmlDsigNamespaceUrl);

            this.Id        = Utils.GetAttribute(value, "Id", EncryptedXml.XmlEncNamespaceUrl);
            this.Type      = Utils.GetAttribute(value, "Type", EncryptedXml.XmlEncNamespaceUrl);
            this.MimeType  = Utils.GetAttribute(value, "MimeType", EncryptedXml.XmlEncNamespaceUrl);
            this.Encoding  = Utils.GetAttribute(value, "Encoding", EncryptedXml.XmlEncNamespaceUrl);
            this.Recipient = Utils.GetAttribute(value, "Recipient", EncryptedXml.XmlEncNamespaceUrl);

            XmlNode encryptionMethodNode = value.SelectSingleNode("enc:EncryptionMethod", nsm);

            // EncryptionMethod
            this.EncryptionMethod = new EncryptionMethod();
            if (encryptionMethodNode != null)
            {
                this.EncryptionMethod.LoadXml(encryptionMethodNode as XmlElement);
            }

            // Key Info
            this.KeyInfo = new KeyInfo();
            XmlNode keyInfoNode = value.SelectSingleNode("ds:KeyInfo", nsm);

            if (keyInfoNode != null)
            {
                this.KeyInfo.LoadXml(keyInfoNode as XmlElement);
            }

            // CipherData
            XmlNode cipherDataNode = value.SelectSingleNode("enc:CipherData", nsm);

            if (cipherDataNode == null)
            {
                throw new CryptographicException(SecurityResources.GetResourceString("Cryptography_Xml_MissingCipherData"));
            }

            this.CipherData = new CipherData();
            this.CipherData.LoadXml(cipherDataNode as XmlElement);

            // EncryptionProperties
            XmlNode encryptionPropertiesNode = value.SelectSingleNode("enc:EncryptionProperties", nsm);

            if (encryptionPropertiesNode != null)
            {
                // Select the EncryptionProperty elements inside the EncryptionProperties element
                XmlNodeList encryptionPropertyNodes = encryptionPropertiesNode.SelectNodes("enc:EncryptionProperty", nsm);
                if (encryptionPropertyNodes != null)
                {
                    foreach (XmlNode node in encryptionPropertyNodes)
                    {
                        EncryptionProperty ep = new EncryptionProperty();
                        ep.LoadXml(node as XmlElement);
                        this.EncryptionProperties.Add(ep);
                    }
                }
            }

            // CarriedKeyName
            XmlNode carriedKeyNameNode = value.SelectSingleNode("enc:CarriedKeyName", nsm);

            if (carriedKeyNameNode != null)
            {
                this.CarriedKeyName = carriedKeyNameNode.InnerText;
            }

            // ReferenceList
            XmlNode referenceListNode = value.SelectSingleNode("enc:ReferenceList", nsm);

            if (referenceListNode != null)
            {
                // Select the DataReference elements inside the ReferenceList element
                XmlNodeList dataReferenceNodes = referenceListNode.SelectNodes("enc:DataReference", nsm);
                if (dataReferenceNodes != null)
                {
                    foreach (XmlNode node in dataReferenceNodes)
                    {
                        DataReference dr = new DataReference();
                        dr.LoadXml(node as XmlElement);
                        this.ReferenceList.Add(dr);
                    }
                }
                // Select the KeyReference elements inside the ReferenceList element
                XmlNodeList keyReferenceNodes = referenceListNode.SelectNodes("enc:KeyReference", nsm);
                if (keyReferenceNodes != null)
                {
                    foreach (XmlNode node in keyReferenceNodes)
                    {
                        KeyReference kr = new KeyReference();
                        kr.LoadXml(node as XmlElement);
                        this.ReferenceList.Add(kr);
                    }
                }
            }

            // Save away the cached value
            m_cachedXml = value;
        }
Esempio n. 9
0
        public void LoadXml(XmlElement value)
        {
            // Make sure we don't get passed null
            if (value == null)
            {
                throw new ArgumentNullException("value");
            }

            // Signature
            XmlElement signatureElement = value;

            if (!signatureElement.LocalName.Equals("Signature"))
            {
                throw new CryptographicException(SecurityResources.GetResourceString("Cryptography_Xml_InvalidElement"), "Signature");
            }

            // Id attribute -- optional
            m_id = Utils.GetAttribute(signatureElement, "Id", SignedXml.XmlDsigNamespaceUrl);

            XmlNamespaceManager nsm = new XmlNamespaceManager(value.OwnerDocument.NameTable);

            nsm.AddNamespace("ds", SignedXml.XmlDsigNamespaceUrl);

            // SignedInfo
            XmlElement signedInfoElement = signatureElement.SelectSingleNode("ds:SignedInfo", nsm) as XmlElement;

            if (signedInfoElement == null)
            {
                throw new CryptographicException(SecurityResources.GetResourceString("Cryptography_Xml_InvalidElement"), "SignedInfo");
            }

            this.SignedInfo = new SignedInfo();
            this.SignedInfo.LoadXml(signedInfoElement);

            // SignatureValue
            XmlElement signatureValueElement = signatureElement.SelectSingleNode("ds:SignatureValue", nsm) as XmlElement;

            if (signatureValueElement == null)
            {
                throw new CryptographicException(SecurityResources.GetResourceString("Cryptography_Xml_InvalidElement"), "SignedInfo/SignatureValue");
            }
            m_signatureValue   = Convert.FromBase64String(Utils.DiscardWhiteSpaces(signatureValueElement.InnerText));
            m_signatureValueId = Utils.GetAttribute(signatureValueElement, "Id", SignedXml.XmlDsigNamespaceUrl);

            XmlNodeList keyInfoNodes = signatureElement.SelectNodes("ds:KeyInfo", nsm);

            m_keyInfo = new KeyInfo();
            if (keyInfoNodes != null)
            {
                foreach (XmlNode node in keyInfoNodes)
                {
                    XmlElement keyInfoElement = node as XmlElement;
                    if (keyInfoElement != null)
                    {
                        m_keyInfo.LoadXml(keyInfoElement);
                    }
                }
            }

            XmlNodeList objectNodes = signatureElement.SelectNodes("ds:Object", nsm);

            m_embeddedObjects.Clear();
            if (objectNodes != null)
            {
                foreach (XmlNode node in objectNodes)
                {
                    XmlElement objectElement = node as XmlElement;
                    if (objectElement != null)
                    {
                        DataObject dataObj = new DataObject();
                        dataObj.LoadXml(objectElement);
                        m_embeddedObjects.Add(dataObj);
                    }
                }
            }

            // Select all elements that have Id attributes
            XmlNodeList nodeList = signatureElement.SelectNodes("//*[@Id]", nsm);

            if (nodeList != null)
            {
                foreach (XmlNode node in nodeList)
                {
                    m_referencedItems.Add(node);
                }
            }
        }
Esempio n. 10
0
        // Encrypts the given element with the key name specified. A corresponding key name mapping
        // has to be defined before calling this method. The key name is added as
        // a KeyNameInfo KeyInfo to an EncryptedKey (AES session key) generated randomly.
        public EncryptedData Encrypt(XmlElement inputElement, string keyName)
        {
            if (inputElement == null)
            {
                throw new ArgumentNullException("inputElement");
            }
            if (keyName == null)
            {
                throw new ArgumentNullException("keyName");
            }

            Object encryptionKey = null;

            if (m_keyNameMapping != null)
            {
                encryptionKey = m_keyNameMapping[keyName];
            }

            if (encryptionKey == null)
            {
                throw new CryptographicException(SecurityResources.GetResourceString("Cryptography_Xml_MissingEncryptionKey"));
            }

            // kek is either a SymmetricAlgorithm or an RSA key, otherwise, we wouldn't be able to insert it in the hash table
            SymmetricAlgorithm symKey = encryptionKey as SymmetricAlgorithm;
            RSA rsa = encryptionKey as RSA;

            // Create the EncryptedData object, using an AES-256 session key by default.
            EncryptedData ed = new EncryptedData();

            ed.Type             = EncryptedXml.XmlEncElementUrl;
            ed.EncryptionMethod = new EncryptionMethod(EncryptedXml.XmlEncAES256Url);

            // Include the key name in the EncryptedKey KeyInfo.
            string encryptionMethod = null;

            if (symKey == null)
            {
                encryptionMethod = EncryptedXml.XmlEncRSA15Url;
            }
            else if (symKey is TripleDES)
            {
                // CMS Triple DES Key Wrap
                encryptionMethod = EncryptedXml.XmlEncTripleDESKeyWrapUrl;
            }
            else if (symKey is Rijndael || symKey is Aes)
            {
                // FIPS AES Key Wrap
                switch (symKey.KeySize)
                {
                case 128:
                    encryptionMethod = EncryptedXml.XmlEncAES128KeyWrapUrl;
                    break;

                case 192:
                    encryptionMethod = EncryptedXml.XmlEncAES192KeyWrapUrl;
                    break;

                case 256:
                    encryptionMethod = EncryptedXml.XmlEncAES256KeyWrapUrl;
                    break;
                }
            }
            else
            {
                // throw an exception if the transform is not in the previous categories
                throw new CryptographicException(SecurityResources.GetResourceString("Cryptography_Xml_NotSupportedCryptographicTransform"));
            }
            EncryptedKey ek = new EncryptedKey();

            ek.EncryptionMethod = new EncryptionMethod(encryptionMethod);
            ek.KeyInfo.AddClause(new KeyInfoName(keyName));

            // Create a random AES session key and encrypt it with the public key associated with the certificate.
            using (Aes aes = Aes.Create()) {
                ek.CipherData.CipherValue = symKey == null?
                                            EncryptedXml.EncryptKey(aes.Key, rsa, false) :
                                                EncryptedXml.EncryptKey(aes.Key, symKey);

                // Encrypt the input element with the random session key that we've created above.
                KeyInfoEncryptedKey kek = new KeyInfoEncryptedKey(ek);
                ed.KeyInfo.AddClause(kek);
                ed.CipherData.CipherValue = EncryptData(inputElement, aes, false);
            }

            return(ed);
        }
Esempio n. 11
0
        // default behaviour is to look for keys defined by an EncryptedKey clause
        // either directly or through a KeyInfoRetrievalMethod, and key names in the key mapping
        public virtual SymmetricAlgorithm GetDecryptionKey(EncryptedData encryptedData, string symmetricAlgorithmUri)
        {
            if (encryptedData == null)
            {
                throw new ArgumentNullException("encryptedData");
            }

            if (encryptedData.KeyInfo == null)
            {
                return(null);
            }
            IEnumerator            keyInfoEnum = encryptedData.KeyInfo.GetEnumerator();
            KeyInfoRetrievalMethod kiRetrievalMethod;
            KeyInfoName            kiName;
            KeyInfoEncryptedKey    kiEncKey;
            EncryptedKey           ek = null;

            while (keyInfoEnum.MoveNext())
            {
                kiName = keyInfoEnum.Current as KeyInfoName;
                if (kiName != null)
                {
                    // Get the decryption key from the key mapping
                    string keyName = kiName.Value;
                    if ((SymmetricAlgorithm)m_keyNameMapping[keyName] != null)
                    {
                        return((SymmetricAlgorithm)m_keyNameMapping[keyName]);
                    }
                    // try to get it from a CarriedKeyName
                    XmlNamespaceManager nsm = new XmlNamespaceManager(m_document.NameTable);
                    nsm.AddNamespace("enc", EncryptedXml.XmlEncNamespaceUrl);
                    XmlNodeList encryptedKeyList = m_document.SelectNodes("//enc:EncryptedKey", nsm);
                    if (encryptedKeyList != null)
                    {
                        foreach (XmlNode encryptedKeyNode in encryptedKeyList)
                        {
                            XmlElement   encryptedKeyElement = encryptedKeyNode as XmlElement;
                            EncryptedKey ek1 = new EncryptedKey();
                            ek1.LoadXml(encryptedKeyElement);
                            if (ek1.CarriedKeyName == keyName && ek1.Recipient == this.Recipient)
                            {
                                ek = ek1;
                                break;
                            }
                        }
                    }
                    break;
                }
                kiRetrievalMethod = keyInfoEnum.Current as KeyInfoRetrievalMethod;
                if (kiRetrievalMethod != null)
                {
                    string idref = Utils.ExtractIdFromLocalUri(kiRetrievalMethod.Uri);
                    ek = new EncryptedKey();
                    ek.LoadXml(GetIdElement(m_document, idref));
                    break;
                }
                kiEncKey = keyInfoEnum.Current as KeyInfoEncryptedKey;
                if (kiEncKey != null)
                {
                    ek = kiEncKey.EncryptedKey;
                    break;
                }
            }

            // if we have an EncryptedKey, decrypt to get the symmetric key
            if (ek != null)
            {
                // now process the EncryptedKey, loop recursively
                // If the Uri is not provided by the application, try to get it from the EncryptionMethod
                if (symmetricAlgorithmUri == null)
                {
                    if (encryptedData.EncryptionMethod == null)
                    {
                        throw new CryptographicException(SecurityResources.GetResourceString("Cryptography_Xml_MissingAlgorithm"));
                    }
                    symmetricAlgorithmUri = encryptedData.EncryptionMethod.KeyAlgorithm;
                }
                byte[] key = DecryptEncryptedKey(ek);
                if (key == null)
                {
                    throw new CryptographicException(SecurityResources.GetResourceString("Cryptography_Xml_MissingDecryptionKey"));
                }

                SymmetricAlgorithm symAlg = Utils.CreateFromName <SymmetricAlgorithm>(symmetricAlgorithmUri);
                if (symAlg == null)
                {
                    throw new CryptographicException(SecurityResources.GetResourceString("Cryptography_Xml_MissingAlgorithm"));
                }
                symAlg.Key = key;
                return(symAlg);
            }
            return(null);
        }
Esempio n. 12
0
        internal byte[] CalculateHashValue(XmlDocument document, CanonicalXmlNodeList refList)
        {
            // refList is a list of elements that might be targets of references
            // Now's the time to create our hashing algorithm
            m_hashAlgorithm = CryptoConfig.CreateFromName(m_digestMethod) as HashAlgorithm;
            if (m_hashAlgorithm == null)
            {
                throw new CryptographicException(SecurityResources.GetResourceString("Cryptography_Xml_CreateHashAlgorithmFailed"));
            }

            // Let's go get the target.
            string      baseUri         = (document == null ? System.Environment.CurrentDirectory + "\\" : document.BaseURI);
            Stream      hashInputStream = null;
            WebRequest  request         = null;
            WebResponse response        = null;
            Stream      inputStream     = null;
            XmlResolver resolver        = null;

            byte[] hashval = null;

            try {
                switch (m_refTargetType)
                {
                case ReferenceTargetType.Stream:
                    // This is the easiest case. We already have a stream, so just pump it through the TransformChain
                    resolver        = (this.SignedXml.ResolverSet ? this.SignedXml.m_xmlResolver : new XmlSecureResolver(new XmlUrlResolver(), baseUri));
                    hashInputStream = this.TransformChain.TransformToOctetStream((Stream)m_refTarget, resolver, baseUri);
                    break;

                case ReferenceTargetType.UriReference:
                    // Second-easiest case -- dereference the URI & pump through the TransformChain
                    // handle the special cases where the URI is null (meaning whole doc)
                    // or the URI is just a fragment (meaning a reference to an embedded Object)
                    if (m_uri == null)
                    {
                        // We need to create a DocumentNavigator out of the XmlElement
                        resolver = (this.SignedXml.ResolverSet ? this.SignedXml.m_xmlResolver : new XmlSecureResolver(new XmlUrlResolver(), baseUri));
                        // In the case of a Uri-less reference, we will simply pass null to the transform chain.
                        // The first transform in the chain is expected to know how to retrieve the data to hash.
                        hashInputStream = this.TransformChain.TransformToOctetStream((Stream)null, resolver, baseUri);
                    }
                    else if (m_uri.Length == 0)
                    {
                        // This is the self-referential case. First, check that we have a document context.
                        // The Enveloped Signature does not discard comments as per spec; those will be omitted during the transform chain process
                        if (document == null)
                        {
                            throw new CryptographicException(String.Format(CultureInfo.CurrentCulture, SecurityResources.GetResourceString("Cryptography_Xml_SelfReferenceRequiresContext"), m_uri));
                        }

                        // Normalize the containing document
                        resolver = (this.SignedXml.ResolverSet ? this.SignedXml.m_xmlResolver : new XmlSecureResolver(new XmlUrlResolver(), baseUri));
                        XmlDocument docWithNoComments = Utils.DiscardComments(Utils.PreProcessDocumentInput(document, resolver, baseUri));
                        hashInputStream = this.TransformChain.TransformToOctetStream(docWithNoComments, resolver, baseUri);
                    }
                    else if (m_uri[0] == '#')
                    {
                        // If we get here, then we are constructing a Reference to an embedded DataObject
                        // referenced by an Id = attribute. Go find the relevant object
                        bool   discardComments = true;
                        string idref           = Utils.GetIdFromLocalUri(m_uri, out discardComments);
                        if (idref == "xpointer(/)")
                        {
                            // This is a self referencial case
                            if (document == null)
                            {
                                throw new CryptographicException(String.Format(CultureInfo.CurrentCulture, SecurityResources.GetResourceString("Cryptography_Xml_SelfReferenceRequiresContext"), m_uri));
                            }

                            // We should not discard comments here!!!
                            resolver        = (this.SignedXml.ResolverSet ? this.SignedXml.m_xmlResolver : new XmlSecureResolver(new XmlUrlResolver(), baseUri));
                            hashInputStream = this.TransformChain.TransformToOctetStream(Utils.PreProcessDocumentInput(document, resolver, baseUri), resolver, baseUri);
                            break;
                        }

                        XmlElement elem = this.SignedXml.GetIdElement(document, idref);
                        if (elem != null)
                        {
                            m_namespaces = Utils.GetPropagatedAttributes(elem.ParentNode as XmlElement);
                        }

                        if (elem == null)
                        {
                            // Go throw the referenced items passed in
                            if (refList != null)
                            {
                                foreach (XmlNode node in refList)
                                {
                                    XmlElement tempElem = node as XmlElement;
                                    if ((tempElem != null) && (Utils.HasAttribute(tempElem, "Id", SignedXml.XmlDsigNamespaceUrl)) &&
                                        (Utils.GetAttribute(tempElem, "Id", SignedXml.XmlDsigNamespaceUrl).Equals(idref)))
                                    {
                                        elem = tempElem;
                                        if (this.m_signedXml.m_context != null)
                                        {
                                            m_namespaces = Utils.GetPropagatedAttributes(this.m_signedXml.m_context);
                                        }
                                        break;
                                    }
                                }
                            }
                        }

                        if (elem == null)
                        {
                            throw new CryptographicException(SecurityResources.GetResourceString("Cryptography_Xml_InvalidReference"));
                        }

                        XmlDocument normDocument = Utils.PreProcessElementInput(elem, resolver, baseUri);
                        // Add the propagated attributes
                        Utils.AddNamespaces(normDocument.DocumentElement, m_namespaces);

                        resolver = (this.SignedXml.ResolverSet ? this.SignedXml.m_xmlResolver : new XmlSecureResolver(new XmlUrlResolver(), baseUri));
                        if (discardComments)
                        {
                            // We should discard comments before going into the transform chain
                            XmlDocument docWithNoComments = Utils.DiscardComments(normDocument);
                            hashInputStream = this.TransformChain.TransformToOctetStream(docWithNoComments, resolver, baseUri);
                        }
                        else
                        {
                            // This is an XPointer reference, do not discard comments!!!
                            hashInputStream = this.TransformChain.TransformToOctetStream(normDocument, resolver, baseUri);
                        }
                    }
                    else if (Utils.AllowDetachedSignature())
                    {
                        // WebRequest always expects an Absolute Uri, so try to resolve if we were passed a relative Uri.
                        System.Uri uri = new System.Uri(m_uri, UriKind.RelativeOrAbsolute);
                        if (!uri.IsAbsoluteUri)
                        {
                            uri = new Uri(new Uri(baseUri), uri);
                        }
                        request = WebRequest.Create(uri);
                        if (request == null)
                        {
                            goto default;
                        }
                        response = request.GetResponse();
                        if (response == null)
                        {
                            goto default;
                        }
                        inputStream = response.GetResponseStream();
                        if (inputStream == null)
                        {
                            goto default;
                        }
                        resolver        = (this.SignedXml.ResolverSet ? this.SignedXml.m_xmlResolver : new XmlSecureResolver(new XmlUrlResolver(), baseUri));
                        hashInputStream = this.TransformChain.TransformToOctetStream(inputStream, resolver, m_uri);
                    }
                    else
                    {
                        throw new CryptographicException(SecurityResources.GetResourceString("Cryptography_Xml_UriNotResolved"), m_uri);
                    }
                    break;

                case ReferenceTargetType.XmlElement:
                    // We need to create a DocumentNavigator out of the XmlElement
                    resolver        = (this.SignedXml.ResolverSet ? this.SignedXml.m_xmlResolver : new XmlSecureResolver(new XmlUrlResolver(), baseUri));
                    hashInputStream = this.TransformChain.TransformToOctetStream(Utils.PreProcessElementInput((XmlElement)m_refTarget, resolver, baseUri), resolver, baseUri);
                    break;

                default:
                    throw new CryptographicException(SecurityResources.GetResourceString("Cryptography_Xml_UriNotResolved"), m_uri);
                }

                // Compute the new hash value
                hashInputStream = SignedXmlDebugLog.LogReferenceData(this, hashInputStream);
                hashval         = m_hashAlgorithm.ComputeHash(hashInputStream);
            }
            finally {
                if (hashInputStream != null)
                {
                    hashInputStream.Close();
                }
                if (response != null)
                {
                    response.Close();
                }
                if (inputStream != null)
                {
                    inputStream.Close();
                }
            }

            return(hashval);
        }
Esempio n. 13
0
        internal unsafe RecipientInfoCollection(SafeCryptMsgHandle safeCryptMsgHandle)
        {
            bool cmsSupported = PkcsUtils.CmsSupported();
            uint dwRecipients = 0;
            uint cbCount      = (uint)Marshal.SizeOf(typeof(uint));

            // Use CMS if supported.
            if (cmsSupported)
            {
                // CMS.
                if (!CAPI.CAPISafe.CryptMsgGetParam(safeCryptMsgHandle,
                                                    CAPI.CMSG_CMS_RECIPIENT_COUNT_PARAM,
                                                    0,
                                                    new IntPtr(&dwRecipients),
                                                    new IntPtr(&cbCount)))
                {
                    throw new CryptographicException(Marshal.GetLastWin32Error());
                }
            }
            else
            {
                // PKCS7.
                if (!CAPI.CAPISafe.CryptMsgGetParam(safeCryptMsgHandle,
                                                    CAPI.CMSG_RECIPIENT_COUNT_PARAM,
                                                    0,
                                                    new IntPtr(&dwRecipients),
                                                    new IntPtr(&cbCount)))
                {
                    throw new CryptographicException(Marshal.GetLastWin32Error());
                }
            }

            m_recipientInfos = new ArrayList();

            for (uint index = 0; index < dwRecipients; index++)
            {
                if (cmsSupported)
                {
                    uint cbCmsRecipientInfo;
                    SafeLocalAllocHandle pbCmsRecipientInfo;

                    PkcsUtils.GetParam(safeCryptMsgHandle, CAPI.CMSG_CMS_RECIPIENT_INFO_PARAM, index, out pbCmsRecipientInfo, out cbCmsRecipientInfo);
                    CAPI.CMSG_CMS_RECIPIENT_INFO cmsRecipientInfo = (CAPI.CMSG_CMS_RECIPIENT_INFO)Marshal.PtrToStructure(pbCmsRecipientInfo.DangerousGetHandle(), typeof(CAPI.CMSG_CMS_RECIPIENT_INFO));

                    switch (cmsRecipientInfo.dwRecipientChoice)
                    {
                    case CAPI.CMSG_KEY_TRANS_RECIPIENT:
                        CAPI.CMSG_KEY_TRANS_RECIPIENT_INFO keyTrans = (CAPI.CMSG_KEY_TRANS_RECIPIENT_INFO)Marshal.PtrToStructure(cmsRecipientInfo.pRecipientInfo, typeof(CAPI.CMSG_KEY_TRANS_RECIPIENT_INFO));
                        m_recipientInfos.Add(new KeyTransRecipientInfo(pbCmsRecipientInfo, keyTrans, index));
                        break;

                    case CAPI.CMSG_KEY_AGREE_RECIPIENT:
                        CAPI.CMSG_KEY_AGREE_RECIPIENT_INFO keyAgree = (CAPI.CMSG_KEY_AGREE_RECIPIENT_INFO)Marshal.PtrToStructure(cmsRecipientInfo.pRecipientInfo, typeof(CAPI.CMSG_KEY_AGREE_RECIPIENT_INFO));
                        switch (keyAgree.dwOriginatorChoice)
                        {
                        case CAPI.CMSG_KEY_AGREE_ORIGINATOR_CERT:
                            CAPI.CMSG_KEY_AGREE_CERT_ID_RECIPIENT_INFO certIdRecipient = (CAPI.CMSG_KEY_AGREE_CERT_ID_RECIPIENT_INFO)Marshal.PtrToStructure(cmsRecipientInfo.pRecipientInfo, typeof(CAPI.CMSG_KEY_AGREE_CERT_ID_RECIPIENT_INFO));
                            for (uint cRecipient = 0; cRecipient < certIdRecipient.cRecipientEncryptedKeys; cRecipient++)
                            {
                                m_recipientInfos.Add(new KeyAgreeRecipientInfo(pbCmsRecipientInfo, certIdRecipient, index, cRecipient));
                            }
                            break;

                        case CAPI.CMSG_KEY_AGREE_ORIGINATOR_PUBLIC_KEY:
                            CAPI.CMSG_KEY_AGREE_PUBLIC_KEY_RECIPIENT_INFO publicKeyRecipient = (CAPI.CMSG_KEY_AGREE_PUBLIC_KEY_RECIPIENT_INFO)Marshal.PtrToStructure(cmsRecipientInfo.pRecipientInfo, typeof(CAPI.CMSG_KEY_AGREE_PUBLIC_KEY_RECIPIENT_INFO));
                            for (uint cRecipient = 0; cRecipient < publicKeyRecipient.cRecipientEncryptedKeys; cRecipient++)
                            {
                                m_recipientInfos.Add(new KeyAgreeRecipientInfo(pbCmsRecipientInfo, publicKeyRecipient, index, cRecipient));
                            }
                            break;

                        default:
                            throw new CryptographicException(SecurityResources.GetResourceString("Cryptography_Cms_Invalid_Originator_Identifier_Choice"), keyAgree.dwOriginatorChoice.ToString(CultureInfo.CurrentCulture));
                        }
                        break;

                    default:
                        throw new CryptographicException(CAPI.E_NOTIMPL);
                    }
                }
                else
                {
                    uint cbCertInfo;
                    SafeLocalAllocHandle pbCertInfo;

                    PkcsUtils.GetParam(safeCryptMsgHandle, CAPI.CMSG_RECIPIENT_INFO_PARAM, index, out pbCertInfo, out cbCertInfo);
                    CAPI.CERT_INFO certInfo = (CAPI.CERT_INFO)Marshal.PtrToStructure(pbCertInfo.DangerousGetHandle(), typeof(CAPI.CERT_INFO));

                    m_recipientInfos.Add(new KeyTransRecipientInfo(pbCertInfo, certInfo, index));
                }
            }

            m_safeCryptMsgHandle = safeCryptMsgHandle;
        }
Esempio n. 14
0
        internal byte[] CalculateHashValue(XmlDocument document, CanonicalXmlNodeList refList)
        {
            this.m_hashAlgorithm = CryptoConfig.CreateFromName(this.m_digestMethod) as HashAlgorithm;
            if (this.m_hashAlgorithm == null)
            {
                throw new CryptographicException(SecurityResources.GetResourceString("Cryptography_Xml_CreateHashAlgorithmFailed"));
            }
            string      securityUrl = (document == null) ? (Environment.CurrentDirectory + @"\") : document.BaseURI;
            Stream      data        = null;
            WebRequest  request     = null;
            WebResponse response    = null;
            Stream      input       = null;
            XmlResolver resolver    = null;

            byte[] buffer = null;
            try
            {
                switch (this.m_refTargetType)
                {
                case System.Security.Cryptography.Xml.ReferenceTargetType.Stream:
                    resolver = this.SignedXml.ResolverSet ? this.SignedXml.m_xmlResolver : new XmlSecureResolver(new XmlUrlResolver(), securityUrl);
                    data     = this.TransformChain.TransformToOctetStream((Stream)this.m_refTarget, resolver, securityUrl);
                    goto Label_048A;

                case System.Security.Cryptography.Xml.ReferenceTargetType.XmlElement:
                    resolver = this.SignedXml.ResolverSet ? this.SignedXml.m_xmlResolver : new XmlSecureResolver(new XmlUrlResolver(), securityUrl);
                    data     = this.TransformChain.TransformToOctetStream(System.Security.Cryptography.Xml.Utils.PreProcessElementInput((XmlElement)this.m_refTarget, resolver, securityUrl), resolver, securityUrl);
                    goto Label_048A;

                case System.Security.Cryptography.Xml.ReferenceTargetType.UriReference:
                    if (this.m_uri != null)
                    {
                        break;
                    }
                    resolver = this.SignedXml.ResolverSet ? this.SignedXml.m_xmlResolver : new XmlSecureResolver(new XmlUrlResolver(), securityUrl);
                    data     = this.TransformChain.TransformToOctetStream((Stream)null, resolver, securityUrl);
                    goto Label_048A;

                default:
                    goto Label_0474;
                }
                if (this.m_uri.Length == 0)
                {
                    if (document == null)
                    {
                        throw new CryptographicException(string.Format(CultureInfo.CurrentCulture, SecurityResources.GetResourceString("Cryptography_Xml_SelfReferenceRequiresContext"), new object[] { this.m_uri }));
                    }
                    resolver = this.SignedXml.ResolverSet ? this.SignedXml.m_xmlResolver : new XmlSecureResolver(new XmlUrlResolver(), securityUrl);
                    XmlDocument document2 = System.Security.Cryptography.Xml.Utils.DiscardComments(System.Security.Cryptography.Xml.Utils.PreProcessDocumentInput(document, resolver, securityUrl));
                    data = this.TransformChain.TransformToOctetStream(document2, resolver, securityUrl);
                    goto Label_048A;
                }
                if (this.m_uri[0] == '#')
                {
                    bool   discardComments = true;
                    string idFromLocalUri  = System.Security.Cryptography.Xml.Utils.GetIdFromLocalUri(this.m_uri, out discardComments);
                    if (idFromLocalUri == "xpointer(/)")
                    {
                        if (document == null)
                        {
                            throw new CryptographicException(string.Format(CultureInfo.CurrentCulture, SecurityResources.GetResourceString("Cryptography_Xml_SelfReferenceRequiresContext"), new object[] { this.m_uri }));
                        }
                        resolver = this.SignedXml.ResolverSet ? this.SignedXml.m_xmlResolver : new XmlSecureResolver(new XmlUrlResolver(), securityUrl);
                        data     = this.TransformChain.TransformToOctetStream(System.Security.Cryptography.Xml.Utils.PreProcessDocumentInput(document, resolver, securityUrl), resolver, securityUrl);
                    }
                    else
                    {
                        XmlElement idElement = this.SignedXml.GetIdElement(document, idFromLocalUri);
                        if (idElement != null)
                        {
                            this.m_namespaces = System.Security.Cryptography.Xml.Utils.GetPropagatedAttributes(idElement.ParentNode as XmlElement);
                        }
                        if ((idElement == null) && (refList != null))
                        {
                            foreach (XmlNode node in refList)
                            {
                                XmlElement element = node as XmlElement;
                                if (((element != null) && System.Security.Cryptography.Xml.Utils.HasAttribute(element, "Id", "http://www.w3.org/2000/09/xmldsig#")) && System.Security.Cryptography.Xml.Utils.GetAttribute(element, "Id", "http://www.w3.org/2000/09/xmldsig#").Equals(idFromLocalUri))
                                {
                                    idElement = element;
                                    if (this.m_signedXml.m_context != null)
                                    {
                                        this.m_namespaces = System.Security.Cryptography.Xml.Utils.GetPropagatedAttributes(this.m_signedXml.m_context);
                                    }
                                    break;
                                }
                            }
                        }
                        if (idElement == null)
                        {
                            throw new CryptographicException(SecurityResources.GetResourceString("Cryptography_Xml_InvalidReference"));
                        }
                        XmlDocument document3 = System.Security.Cryptography.Xml.Utils.PreProcessElementInput(idElement, resolver, securityUrl);
                        System.Security.Cryptography.Xml.Utils.AddNamespaces(document3.DocumentElement, this.m_namespaces);
                        resolver = this.SignedXml.ResolverSet ? this.SignedXml.m_xmlResolver : new XmlSecureResolver(new XmlUrlResolver(), securityUrl);
                        if (discardComments)
                        {
                            XmlDocument document4 = System.Security.Cryptography.Xml.Utils.DiscardComments(document3);
                            data = this.TransformChain.TransformToOctetStream(document4, resolver, securityUrl);
                        }
                        else
                        {
                            data = this.TransformChain.TransformToOctetStream(document3, resolver, securityUrl);
                        }
                    }
                    goto Label_048A;
                }
                System.Uri relativeUri = new System.Uri(this.m_uri, UriKind.RelativeOrAbsolute);
                if (!relativeUri.IsAbsoluteUri)
                {
                    relativeUri = new System.Uri(new System.Uri(securityUrl), relativeUri);
                }
                request = WebRequest.Create(relativeUri);
                if (request != null)
                {
                    response = request.GetResponse();
                    if (response != null)
                    {
                        input = response.GetResponseStream();
                        if (input != null)
                        {
                            resolver = this.SignedXml.ResolverSet ? this.SignedXml.m_xmlResolver : new XmlSecureResolver(new XmlUrlResolver(), securityUrl);
                            data     = this.TransformChain.TransformToOctetStream(input, resolver, this.m_uri);
                            goto Label_048A;
                        }
                    }
                }
Label_0474:
                throw new CryptographicException(SecurityResources.GetResourceString("Cryptography_Xml_UriNotResolved"), this.m_uri);
Label_048A:
                data   = SignedXmlDebugLog.LogReferenceData(this, data);
                buffer = this.m_hashAlgorithm.ComputeHash(data);
            }
            finally
            {
                if (data != null)
                {
                    data.Close();
                }
                if (response != null)
                {
                    response.Close();
                }
                if (input != null)
                {
                    input.Close();
                }
            }
            return(buffer);
        }
Esempio n. 15
0
        public void LoadXml(XmlElement value)
        {
            if (value == null)
            {
                throw new ArgumentNullException("value");
            }
            this.m_id   = System.Security.Cryptography.Xml.Utils.GetAttribute(value, "Id", "http://www.w3.org/2000/09/xmldsig#");
            this.m_uri  = System.Security.Cryptography.Xml.Utils.GetAttribute(value, "URI", "http://www.w3.org/2000/09/xmldsig#");
            this.m_type = System.Security.Cryptography.Xml.Utils.GetAttribute(value, "Type", "http://www.w3.org/2000/09/xmldsig#");
            XmlNamespaceManager nsmgr = new XmlNamespaceManager(value.OwnerDocument.NameTable);

            nsmgr.AddNamespace("ds", "http://www.w3.org/2000/09/xmldsig#");
            this.TransformChain = new System.Security.Cryptography.Xml.TransformChain();
            XmlElement element = value.SelectSingleNode("ds:Transforms", nsmgr) as XmlElement;

            if (element != null)
            {
                XmlNodeList list = element.SelectNodes("ds:Transform", nsmgr);
                if (list != null)
                {
                    foreach (XmlNode node in list)
                    {
                        XmlElement element2  = node as XmlElement;
                        Transform  transform = CryptoConfig.CreateFromName(System.Security.Cryptography.Xml.Utils.GetAttribute(element2, "Algorithm", "http://www.w3.org/2000/09/xmldsig#")) as Transform;
                        if (transform == null)
                        {
                            throw new CryptographicException(SecurityResources.GetResourceString("Cryptography_Xml_UnknownTransform"));
                        }
                        this.AddTransform(transform);
                        transform.LoadInnerXml(element2.ChildNodes);
                        if (transform is XmlDsigEnvelopedSignatureTransform)
                        {
                            XmlNode     node2 = element2.SelectSingleNode("ancestor::ds:Signature[1]", nsmgr);
                            XmlNodeList list2 = element2.SelectNodes("//ds:Signature", nsmgr);
                            if (list2 != null)
                            {
                                int num = 0;
                                foreach (XmlNode node3 in list2)
                                {
                                    num++;
                                    if (node3 == node2)
                                    {
                                        ((XmlDsigEnvelopedSignatureTransform)transform).SignaturePosition = num;
                                        break;
                                    }
                                }
                            }
                        }
                    }
                }
            }
            XmlElement element3 = value.SelectSingleNode("ds:DigestMethod", nsmgr) as XmlElement;

            if (element3 == null)
            {
                throw new CryptographicException(SecurityResources.GetResourceString("Cryptography_Xml_InvalidElement"), "Reference/DigestMethod");
            }
            this.m_digestMethod = System.Security.Cryptography.Xml.Utils.GetAttribute(element3, "Algorithm", "http://www.w3.org/2000/09/xmldsig#");
            XmlElement element4 = value.SelectSingleNode("ds:DigestValue", nsmgr) as XmlElement;

            if (element4 == null)
            {
                throw new CryptographicException(SecurityResources.GetResourceString("Cryptography_Xml_InvalidElement"), "Reference/DigestValue");
            }
            this.m_digestValue = Convert.FromBase64String(System.Security.Cryptography.Xml.Utils.DiscardWhiteSpaces(element4.InnerText));
            this.m_cachedXml   = value;
        }
        internal XmlElement GetXml(XmlDocument document)
        {
            XmlElement element = document.CreateElement("EncryptedKey", "http://www.w3.org/2001/04/xmlenc#");

            if (!string.IsNullOrEmpty(this.Id))
            {
                element.SetAttribute("Id", this.Id);
            }
            if (!string.IsNullOrEmpty(this.Type))
            {
                element.SetAttribute("Type", this.Type);
            }
            if (!string.IsNullOrEmpty(this.MimeType))
            {
                element.SetAttribute("MimeType", this.MimeType);
            }
            if (!string.IsNullOrEmpty(this.Encoding))
            {
                element.SetAttribute("Encoding", this.Encoding);
            }
            if (!string.IsNullOrEmpty(this.Recipient))
            {
                element.SetAttribute("Recipient", this.Recipient);
            }
            if (this.EncryptionMethod != null)
            {
                element.AppendChild(this.EncryptionMethod.GetXml(document));
            }
            if (base.KeyInfo.Count > 0)
            {
                element.AppendChild(base.KeyInfo.GetXml(document));
            }
            if (this.CipherData == null)
            {
                throw new CryptographicException(SecurityResources.GetResourceString("Cryptography_Xml_MissingCipherData"));
            }
            element.AppendChild(this.CipherData.GetXml(document));
            if (this.EncryptionProperties.Count > 0)
            {
                XmlElement newChild = document.CreateElement("EncryptionProperties", "http://www.w3.org/2001/04/xmlenc#");
                for (int i = 0; i < this.EncryptionProperties.Count; i++)
                {
                    EncryptionProperty property = this.EncryptionProperties.Item(i);
                    newChild.AppendChild(property.GetXml(document));
                }
                element.AppendChild(newChild);
            }
            if (this.ReferenceList.Count > 0)
            {
                XmlElement element3 = document.CreateElement("ReferenceList", "http://www.w3.org/2001/04/xmlenc#");
                for (int j = 0; j < this.ReferenceList.Count; j++)
                {
                    element3.AppendChild(this.ReferenceList[j].GetXml(document));
                }
                element.AppendChild(element3);
            }
            if (this.CarriedKeyName != null)
            {
                XmlElement element4 = document.CreateElement("CarriedKeyName", "http://www.w3.org/2001/04/xmlenc#");
                XmlText    text     = document.CreateTextNode(this.CarriedKeyName);
                element4.AppendChild(text);
                element.AppendChild(element4);
            }
            return(element);
        }
Esempio n. 17
0
        public void LoadXml(XmlElement value)
        {
            if (value == null)
            {
                throw new ArgumentNullException("value");
            }

            m_id   = Utils.GetAttribute(value, "Id", SignedXml.XmlDsigNamespaceUrl);
            m_uri  = Utils.GetAttribute(value, "URI", SignedXml.XmlDsigNamespaceUrl);
            m_type = Utils.GetAttribute(value, "Type", SignedXml.XmlDsigNamespaceUrl);

            XmlNamespaceManager nsm = new XmlNamespaceManager(value.OwnerDocument.NameTable);

            nsm.AddNamespace("ds", SignedXml.XmlDsigNamespaceUrl);

            // Transforms
            this.TransformChain = new TransformChain();
            XmlElement transformsElement = value.SelectSingleNode("ds:Transforms", nsm) as XmlElement;

            if (transformsElement != null)
            {
                XmlNodeList transformNodes = transformsElement.SelectNodes("ds:Transform", nsm);
                if (transformNodes != null)
                {
                    foreach (XmlNode transformNode in transformNodes)
                    {
                        XmlElement transformElement = transformNode as XmlElement;
                        string     algorithm        = Utils.GetAttribute(transformElement, "Algorithm", SignedXml.XmlDsigNamespaceUrl);
                        Transform  transform        = CryptoConfig.CreateFromName(algorithm) as Transform;
                        if (transform == null)
                        {
                            throw new CryptographicException(SecurityResources.GetResourceString("Cryptography_Xml_UnknownTransform"));
                        }
                        AddTransform(transform);
                        // let the transform read the children of the transformElement for data
                        transform.LoadInnerXml(transformElement.ChildNodes);
                        // Hack! this is done to get around the lack of here() function support in XPath
                        if (transform is XmlDsigEnvelopedSignatureTransform)
                        {
                            // Walk back to the Signature tag. Find the nearest signature ancestor
                            // Signature-->SignedInfo-->Reference-->Transforms-->Transform
                            XmlNode     signatureTag  = transformElement.SelectSingleNode("ancestor::ds:Signature[1]", nsm);
                            XmlNodeList signatureList = transformElement.SelectNodes("//ds:Signature", nsm);
                            if (signatureList != null)
                            {
                                int position = 0;
                                foreach (XmlNode node in signatureList)
                                {
                                    position++;
                                    if (node == signatureTag)
                                    {
                                        ((XmlDsigEnvelopedSignatureTransform)transform).SignaturePosition = position;
                                        break;
                                    }
                                }
                            }
                        }
                    }
                }
            }

            // DigestMethod
            XmlElement digestMethodElement = value.SelectSingleNode("ds:DigestMethod", nsm) as XmlElement;

            if (digestMethodElement == null)
            {
                throw new CryptographicException(SecurityResources.GetResourceString("Cryptography_Xml_InvalidElement"), "Reference/DigestMethod");
            }
            m_digestMethod = Utils.GetAttribute(digestMethodElement, "Algorithm", SignedXml.XmlDsigNamespaceUrl);

            // DigestValue
            XmlElement digestValueElement = value.SelectSingleNode("ds:DigestValue", nsm) as XmlElement;

            if (digestValueElement == null)
            {
                throw new CryptographicException(SecurityResources.GetResourceString("Cryptography_Xml_InvalidElement"), "Reference/DigestValue");
            }
            m_digestValue = Convert.FromBase64String(Utils.DiscardWhiteSpaces(digestValueElement.InnerText));

            // cache the Xml
            m_cachedXml = value;
        }
Esempio n. 18
0
        // The goal behind this method is to pump the input stream through the transforms and get back something that
        // can be hashed
        internal Stream TransformToOctetStream(object inputObject, Type inputType, XmlResolver resolver, string baseUri)
        {
            object currentInput = inputObject;

            foreach (Transform transform in _transforms)
            {
                if (currentInput == null || transform.AcceptsType(currentInput.GetType()))
                {
                    //in this case, no translation necessary, pump it through
                    transform.Resolver = resolver;
                    transform.BaseURI  = baseUri;
                    transform.LoadInput(currentInput);
                    currentInput = transform.GetOutput();
                }
                else
                {
                    // We need translation
                    // For now, we just know about Stream->{XmlNodeList,XmlDocument} and {XmlNodeList,XmlDocument}->Stream
                    if (currentInput is Stream)
                    {
                        if (transform.AcceptsType(typeof(XmlDocument)))
                        {
                            Stream      currentInputStream = currentInput as Stream;
                            XmlDocument doc = new XmlDocument();
                            doc.PreserveWhitespace = true;
                            XmlReader valReader = Utils.PreProcessStreamInput(currentInputStream, resolver, baseUri);
                            doc.Load(valReader);
                            transform.LoadInput(doc);
                            currentInputStream.Close();
                            currentInput = transform.GetOutput();
                            continue;
                        }
                        else
                        {
                            throw new CryptographicException(SecurityResources.GetResourceString("Cryptography_Xml_TransformIncorrectInputType"));
                        }
                    }
                    if (currentInput is XmlNodeList)
                    {
                        if (transform.AcceptsType(typeof(Stream)))
                        {
                            CanonicalXml c14n = new CanonicalXml((XmlNodeList)currentInput, resolver, false);
                            MemoryStream ms   = new MemoryStream(c14n.GetBytes());
                            transform.LoadInput(ms);
                            currentInput = transform.GetOutput();
                            ms.Close();
                            continue;
                        }
                        else
                        {
                            throw new CryptographicException(SecurityResources.GetResourceString("Cryptography_Xml_TransformIncorrectInputType"));
                        }
                    }
                    if (currentInput is XmlDocument)
                    {
                        if (transform.AcceptsType(typeof(Stream)))
                        {
                            CanonicalXml c14n = new CanonicalXml((XmlDocument)currentInput, resolver);
                            MemoryStream ms   = new MemoryStream(c14n.GetBytes());
                            transform.LoadInput(ms);
                            currentInput = transform.GetOutput();
                            ms.Close();
                            continue;
                        }
                        else
                        {
                            throw new CryptographicException(SecurityResources.GetResourceString("Cryptography_Xml_TransformIncorrectInputType"));
                        }
                    }
                    throw new CryptographicException(SecurityResources.GetResourceString("Cryptography_Xml_TransformIncorrectInputType"));
                }
            }

            // Final processing, either we already have a stream or have to canonicalize
            if (currentInput is Stream)
            {
                return(currentInput as Stream);
            }
            if (currentInput is XmlNodeList)
            {
                CanonicalXml c14n = new CanonicalXml((XmlNodeList)currentInput, resolver, false);
                MemoryStream ms   = new MemoryStream(c14n.GetBytes());
                return(ms);
            }
            if (currentInput is XmlDocument)
            {
                CanonicalXml c14n = new CanonicalXml((XmlDocument)currentInput, resolver);
                MemoryStream ms   = new MemoryStream(c14n.GetBytes());
                return(ms);
            }
            throw new CryptographicException(SecurityResources.GetResourceString("Cryptography_Xml_TransformIncorrectInputType"));
        }
Esempio n. 19
0
        //
        // private methods
        //

        private byte[] GetCipherValue(CipherData cipherData)
        {
            if (cipherData == null)
            {
                throw new ArgumentNullException("cipherData");
            }

            WebResponse response    = null;
            Stream      inputStream = null;

            if (cipherData.CipherValue != null)
            {
                return(cipherData.CipherValue);
            }
            else if (cipherData.CipherReference != null)
            {
                if (cipherData.CipherReference.CipherValue != null)
                {
                    return(cipherData.CipherReference.CipherValue);
                }
                Stream decInputStream = null;
                // See if the CipherReference is a local URI
                if (!Utils.GetLeaveCipherValueUnchecked() && cipherData.CipherReference.Uri == null)
                {
                    throw new CryptographicException(SecurityResources.GetResourceString("Cryptography_Xml_UriNotSupported"));
                }
                if (cipherData.CipherReference.Uri.Length == 0)
                {
                    // self referenced Uri
                    string         baseUri = (m_document == null ? null : m_document.BaseURI);
                    TransformChain tc      = cipherData.CipherReference.TransformChain;
                    if (!Utils.GetLeaveCipherValueUnchecked() && tc == null)
                    {
                        throw new CryptographicException(SecurityResources.GetResourceString("Cryptography_Xml_UriNotSupported"));
                    }
                    decInputStream = tc.TransformToOctetStream(m_document, m_xmlResolver, baseUri);
                }
                else if (cipherData.CipherReference.Uri[0] == '#')
                {
                    string idref = Utils.ExtractIdFromLocalUri(cipherData.CipherReference.Uri);
                    // Serialize
                    if (Utils.GetLeaveCipherValueUnchecked())
                    {
                        inputStream = new MemoryStream(m_encoding.GetBytes(GetIdElement(m_document, idref).OuterXml));
                    }
                    else
                    {
                        XmlElement idElem = GetIdElement(m_document, idref);
                        if (idElem == null || idElem.OuterXml == null)
                        {
                            throw new CryptographicException(SecurityResources.GetResourceString("Cryptography_Xml_UriNotSupported"));
                        }
                        inputStream = new MemoryStream(m_encoding.GetBytes(idElem.OuterXml));
                    }

                    string         baseUri = (m_document == null ? null : m_document.BaseURI);
                    TransformChain tc      = cipherData.CipherReference.TransformChain;
                    if (!Utils.GetLeaveCipherValueUnchecked() && tc == null)
                    {
                        throw new CryptographicException(SecurityResources.GetResourceString("Cryptography_Xml_UriNotSupported"));
                    }
                    decInputStream = tc.TransformToOctetStream(inputStream, m_xmlResolver, baseUri);
                }
                else
                {
                    DownloadCipherValue(cipherData, out inputStream, out decInputStream, out response);
                }
                // read the output stream into a memory stream
                byte[] cipherValue = null;
                using (MemoryStream ms = new MemoryStream()) {
                    Utils.Pump(decInputStream, ms);
                    cipherValue = ms.ToArray();
                    // Close the stream and return
                    if (response != null)
                    {
                        response.Close();
                    }
                    if (inputStream != null)
                    {
                        inputStream.Close();
                    }
                    decInputStream.Close();
                }

                // cache the cipher value for Perf reasons in case we call this routine twice
                cipherData.CipherReference.CipherValue = cipherValue;
                return(cipherValue);
            }

            // Throw a CryptographicException if we were unable to retrieve the cipher data.
            throw new CryptographicException(SecurityResources.GetResourceString("Cryptography_Xml_MissingCipherData"));
        }
Esempio n. 20
0
        internal RecipientInfoCollection(SafeCryptMsgHandle safeCryptMsgHandle)
        {
            bool flag = PkcsUtils.CmsSupported();
            uint num1 = 0U;
            uint num2 = (uint)Marshal.SizeOf(typeof(uint));

            if (flag)
            {
                if (!CAPI.CAPISafe.CryptMsgGetParam(safeCryptMsgHandle, 33U, 0U, new IntPtr((void *)&num1), new IntPtr((void *)&num2)))
                {
                    throw new CryptographicException(Marshal.GetLastWin32Error());
                }
            }
            else if (!CAPI.CAPISafe.CryptMsgGetParam(safeCryptMsgHandle, 17U, 0U, new IntPtr((void *)&num1), new IntPtr((void *)&num2)))
            {
                throw new CryptographicException(Marshal.GetLastWin32Error());
            }
            this.m_recipientInfos = new ArrayList();
            for (uint index = 0U; index < num1; ++index)
            {
                if (flag)
                {
                    SafeLocalAllocHandle pvData;
                    uint cbData;
                    PkcsUtils.GetParam(safeCryptMsgHandle, 36U, index, out pvData, out cbData);
                    CAPI.CMSG_CMS_RECIPIENT_INFO cmsRecipientInfo = (CAPI.CMSG_CMS_RECIPIENT_INFO)Marshal.PtrToStructure(pvData.DangerousGetHandle(), typeof(CAPI.CMSG_CMS_RECIPIENT_INFO));
                    switch (cmsRecipientInfo.dwRecipientChoice)
                    {
                    case 1U:
                        CAPI.CMSG_KEY_TRANS_RECIPIENT_INFO keyTrans = (CAPI.CMSG_KEY_TRANS_RECIPIENT_INFO)Marshal.PtrToStructure(cmsRecipientInfo.pRecipientInfo, typeof(CAPI.CMSG_KEY_TRANS_RECIPIENT_INFO));
                        this.m_recipientInfos.Add((object)new KeyTransRecipientInfo(pvData, keyTrans, index));
                        continue;

                    case 2U:
                        CAPI.CMSG_KEY_AGREE_RECIPIENT_INFO agreeRecipientInfo = (CAPI.CMSG_KEY_AGREE_RECIPIENT_INFO)Marshal.PtrToStructure(cmsRecipientInfo.pRecipientInfo, typeof(CAPI.CMSG_KEY_AGREE_RECIPIENT_INFO));
                        switch (agreeRecipientInfo.dwOriginatorChoice)
                        {
                        case 1U:
                            CAPI.CMSG_KEY_AGREE_CERT_ID_RECIPIENT_INFO certIdRecipient = (CAPI.CMSG_KEY_AGREE_CERT_ID_RECIPIENT_INFO)Marshal.PtrToStructure(cmsRecipientInfo.pRecipientInfo, typeof(CAPI.CMSG_KEY_AGREE_CERT_ID_RECIPIENT_INFO));
                            for (uint subIndex = 0U; subIndex < certIdRecipient.cRecipientEncryptedKeys; ++subIndex)
                            {
                                this.m_recipientInfos.Add((object)new KeyAgreeRecipientInfo(pvData, certIdRecipient, index, subIndex));
                            }
                            continue;

                        case 2U:
                            CAPI.CMSG_KEY_AGREE_PUBLIC_KEY_RECIPIENT_INFO publicKeyRecipient = (CAPI.CMSG_KEY_AGREE_PUBLIC_KEY_RECIPIENT_INFO)Marshal.PtrToStructure(cmsRecipientInfo.pRecipientInfo, typeof(CAPI.CMSG_KEY_AGREE_PUBLIC_KEY_RECIPIENT_INFO));
                            for (uint subIndex = 0U; subIndex < publicKeyRecipient.cRecipientEncryptedKeys; ++subIndex)
                            {
                                this.m_recipientInfos.Add((object)new KeyAgreeRecipientInfo(pvData, publicKeyRecipient, index, subIndex));
                            }
                            continue;

                        default:
                            throw new CryptographicException(SecurityResources.GetResourceString("Cryptography_Cms_Invalid_Originator_Identifier_Choice"), agreeRecipientInfo.dwOriginatorChoice.ToString((IFormatProvider)CultureInfo.CurrentCulture));
                        }

                    default:
                        throw new CryptographicException(-2147483647);
                    }
                }
                else
                {
                    SafeLocalAllocHandle pvData;
                    uint cbData;
                    PkcsUtils.GetParam(safeCryptMsgHandle, 19U, index, out pvData, out cbData);
                    CAPI.CERT_INFO certInfo = (CAPI.CERT_INFO)Marshal.PtrToStructure(pvData.DangerousGetHandle(), typeof(CAPI.CERT_INFO));
                    this.m_recipientInfos.Add((object)new KeyTransRecipientInfo(pvData, certInfo, index));
                }
            }
            this.m_safeCryptMsgHandle = safeCryptMsgHandle;
        }
Esempio n. 21
0
        // Try to decrypt the EncryptedKey given the key mapping
        public virtual byte[] DecryptEncryptedKey(EncryptedKey encryptedKey)
        {
            if (encryptedKey == null)
            {
                throw new ArgumentNullException("encryptedKey");
            }
            if (encryptedKey.KeyInfo == null)
            {
                return(null);
            }

            IEnumerator            keyInfoEnum = encryptedKey.KeyInfo.GetEnumerator();
            KeyInfoName            kiName;
            KeyInfoX509Data        kiX509Data;
            KeyInfoRetrievalMethod kiRetrievalMethod;
            KeyInfoEncryptedKey    kiEncKey;
            EncryptedKey           ek = null;
            bool fOAEP = false;

            while (keyInfoEnum.MoveNext())
            {
                kiName = keyInfoEnum.Current as KeyInfoName;
                if (kiName != null)
                {
                    // Get the decryption key from the key mapping
                    string keyName = kiName.Value;
                    Object kek     = m_keyNameMapping[keyName];
                    if (kek != null)
                    {
                        if (!Utils.GetLeaveCipherValueUnchecked() && (encryptedKey.CipherData == null || encryptedKey.CipherData.CipherValue == null))
                        {
                            throw new CryptographicException(SecurityResources.GetResourceString("Cryptography_Xml_MissingAlgorithm"));
                        }
                        // kek is either a SymmetricAlgorithm or an RSA key, otherwise, we wouldn't be able to insert it in the hash table
                        if (kek is SymmetricAlgorithm)
                        {
                            return(EncryptedXml.DecryptKey(encryptedKey.CipherData.CipherValue, (SymmetricAlgorithm)kek));
                        }

                        // kek is an RSA key: get fOAEP from the algorithm, default to false
                        fOAEP = (encryptedKey.EncryptionMethod != null && encryptedKey.EncryptionMethod.KeyAlgorithm == EncryptedXml.XmlEncRSAOAEPUrl);
                        return(EncryptedXml.DecryptKey(encryptedKey.CipherData.CipherValue, (RSA)kek, fOAEP));
                    }
                    break;
                }
                kiX509Data = keyInfoEnum.Current as KeyInfoX509Data;
                if (kiX509Data != null)
                {
                    X509Certificate2Collection collection = Utils.BuildBagOfCerts(kiX509Data, CertUsageType.Decryption);
                    foreach (X509Certificate2 certificate in collection)
                    {
                        using (RSA privateKey = certificate.GetRSAPrivateKey()) {
                            if (privateKey != null)
                            {
                                if (!Utils.GetLeaveCipherValueUnchecked() && (encryptedKey.CipherData == null || encryptedKey.CipherData.CipherValue == null))
                                {
                                    throw new CryptographicException(SecurityResources.GetResourceString("Cryptography_Xml_MissingAlgorithm"));
                                }
                                fOAEP = (encryptedKey.EncryptionMethod != null && encryptedKey.EncryptionMethod.KeyAlgorithm == EncryptedXml.XmlEncRSAOAEPUrl);
                                return(EncryptedXml.DecryptKey(encryptedKey.CipherData.CipherValue, privateKey, fOAEP));
                            }
                        }
                    }
                    break;
                }
                kiRetrievalMethod = keyInfoEnum.Current as KeyInfoRetrievalMethod;
                if (kiRetrievalMethod != null)
                {
                    string idref = Utils.ExtractIdFromLocalUri(kiRetrievalMethod.Uri);
                    ek = new EncryptedKey();
                    ek.LoadXml(GetIdElement(m_document, idref));
                    try {
                        //Following checks if XML dsig processing is in loop and within the limit defined by machine
                        // admin or developer. Once the recursion depth crosses the defined limit it will throw exception.
                        m_xmlDsigSearchDepthCounter++;
                        if (IsOverXmlDsigRecursionLimit())
                        {
                            //Throw exception once recursion limit is hit.
                            throw new CryptoSignedXmlRecursionException();
                        }
                        else
                        {
                            return(DecryptEncryptedKey(ek));
                        }
                    }
                    finally {
                        m_xmlDsigSearchDepthCounter--;
                    }
                }
                kiEncKey = keyInfoEnum.Current as KeyInfoEncryptedKey;
                if (kiEncKey != null)
                {
                    ek = kiEncKey.EncryptedKey;
                    // recursively process EncryptedKey elements
                    byte[] encryptionKey = DecryptEncryptedKey(ek);
                    if (encryptionKey != null)
                    {
                        // this is a symmetric algorithm for sure
                        SymmetricAlgorithm symAlg = Utils.CreateFromName <SymmetricAlgorithm>(encryptedKey.EncryptionMethod.KeyAlgorithm);
                        if (symAlg == null)
                        {
                            throw new CryptographicException(SecurityResources.GetResourceString("Cryptography_Xml_MissingAlgorithm"));
                        }
                        symAlg.Key = encryptionKey;
                        if (!Utils.GetLeaveCipherValueUnchecked() && (encryptedKey.CipherData == null || encryptedKey.CipherData.CipherValue == null))
                        {
                            throw new CryptographicException(SecurityResources.GetResourceString("Cryptography_Xml_MissingAlgorithm"));
                        }
                        return(EncryptedXml.DecryptKey(encryptedKey.CipherData.CipherValue, symAlg));
                    }
                }
            }
            return(null);
        }
Esempio n. 22
0
        public void ComputeSignature(KeyedHashAlgorithm macAlg)
        {
            if (macAlg == null)
            {
                throw new ArgumentNullException("macAlg");
            }

            HMAC hash = macAlg as HMAC;

            if (hash == null)
            {
                throw new CryptographicException(SecurityResources.GetResourceString("Cryptography_Xml_SignatureMethodKeyMismatch"));
            }

            int signatureLength;

            if (m_signature.SignedInfo.SignatureLength == null)
            {
                signatureLength = hash.HashSize;
            }
            else
            {
                signatureLength = Convert.ToInt32(m_signature.SignedInfo.SignatureLength, null);
            }
            // signatureLength should be less than hash size
            if (signatureLength < 0 || signatureLength > hash.HashSize)
            {
                throw new CryptographicException(SecurityResources.GetResourceString("Cryptography_Xml_InvalidSignatureLength"));
            }
            if (signatureLength % 8 != 0)
            {
                throw new CryptographicException(SecurityResources.GetResourceString("Cryptography_Xml_InvalidSignatureLength2"));
            }

            BuildDigestedReferences();
            switch (hash.HashName)
            {
            case "SHA1":
                SignedInfo.SignatureMethod = SignedXml.XmlDsigHMACSHA1Url;
                break;

            case "SHA256":
                SignedInfo.SignatureMethod = SignedXml.XmlDsigMoreHMACSHA256Url;
                break;

            case "SHA384":
                SignedInfo.SignatureMethod = SignedXml.XmlDsigMoreHMACSHA384Url;
                break;

            case "SHA512":
                SignedInfo.SignatureMethod = SignedXml.XmlDsigMoreHMACSHA512Url;
                break;

            case "MD5":
                SignedInfo.SignatureMethod = SignedXml.XmlDsigMoreHMACMD5Url;
                break;

            case "RIPEMD160":
                SignedInfo.SignatureMethod = SignedXml.XmlDsigMoreHMACRIPEMD160Url;
                break;

            default:
                throw new CryptographicException(SecurityResources.GetResourceString("Cryptography_Xml_SignatureMethodKeyMismatch"));
            }

            byte[] hashValue = GetC14NDigest(hash);

            m_signature.SignatureValue = new byte[signatureLength / 8];
            Buffer.BlockCopy(hashValue, 0, m_signature.SignatureValue, 0, signatureLength / 8);
        }
        private void DecryptEncryptedGrants(XmlNodeList encryptedGrantList, IRelDecryptor decryptor)
        {
            XmlElement       element          = null;
            XmlElement       element2         = null;
            XmlElement       element3         = null;
            EncryptionMethod encryptionMethod = null;
            KeyInfo          keyInfo          = null;
            CipherData       data             = null;
            int num   = 0;
            int count = encryptedGrantList.Count;

            while (num < count)
            {
                element  = encryptedGrantList[num].SelectSingleNode("//r:encryptedGrant/enc:EncryptionMethod", this.namespaceManager) as XmlElement;
                element2 = encryptedGrantList[num].SelectSingleNode("//r:encryptedGrant/dsig:KeyInfo", this.namespaceManager) as XmlElement;
                element3 = encryptedGrantList[num].SelectSingleNode("//r:encryptedGrant/enc:CipherData", this.namespaceManager) as XmlElement;
                if (((element != null) && (element2 != null)) && (element3 != null))
                {
                    encryptionMethod = new EncryptionMethod();
                    keyInfo          = new KeyInfo();
                    data             = new CipherData();
                    encryptionMethod.LoadXml(element);
                    keyInfo.LoadXml(element2);
                    data.LoadXml(element3);
                    MemoryStream toDecrypt = null;
                    Stream       stream    = null;
                    StreamReader reader    = null;
                    try
                    {
                        toDecrypt = new MemoryStream(data.CipherValue);
                        stream    = this.relDecryptor.Decrypt(encryptionMethod, keyInfo, toDecrypt);
                        if ((stream == null) || (stream.Length == 0L))
                        {
                            throw new CryptographicException(SecurityResources.GetResourceString("Cryptography_Xml_XrmlUnableToDecryptGrant"));
                        }
                        reader = new StreamReader(stream);
                        string str = reader.ReadToEnd();
                        encryptedGrantList[num].ParentNode.InnerXml = str;
                    }
                    finally
                    {
                        if (toDecrypt != null)
                        {
                            toDecrypt.Close();
                        }
                        if (stream != null)
                        {
                            stream.Close();
                        }
                        if (reader != null)
                        {
                            reader.Close();
                        }
                    }
                    encryptionMethod = null;
                    keyInfo          = null;
                    data             = null;
                }
                element  = null;
                element2 = null;
                element3 = null;
                num++;
            }
        }
Esempio n. 24
0
        public void ComputeSignature(CmsSigner signer, bool silent)
        {
            if (signer == null)
            {
                throw new ArgumentNullException("signer");
            }
            if (ContentInfo.Content.Length == 0)
            {
                throw new CryptographicException(SecurityResources.GetResourceString("Cryptography_Cms_Sign_Empty_Content"));
            }

            if (SubjectIdentifierType.NoSignature == signer.SignerIdentifierType)
            {
                if (m_safeCryptMsgHandle != null && !m_safeCryptMsgHandle.IsInvalid)
                {
                    throw new CryptographicException(SecurityResources.GetResourceString("Cryptography_Cms_Sign_No_Signature_First_Signer"));
                }

                // First signer.
                Sign(signer, silent);
                return;
            }

            if (signer.Certificate == null)
            {
                if (silent)
                {
                    throw new InvalidOperationException(SecurityResources.GetResourceString("Cryptography_Cms_RecipientCertificateNotFound"));
                }
                else
                {
                    signer.Certificate = PkcsUtils.SelectSignerCertificate();
                }
            }

            if (!signer.Certificate.HasPrivateKey)
            {
                throw new CryptographicException(CAPI.NTE_NO_KEY);
            }

            //



            CspParameters parameters = new CspParameters();

            if (X509Utils.GetPrivateKeyInfo(X509Utils.GetCertContext(signer.Certificate), ref parameters))
            {
                KeyContainerPermission            kp    = new KeyContainerPermission(KeyContainerPermissionFlags.NoFlags);
                KeyContainerPermissionAccessEntry entry = new KeyContainerPermissionAccessEntry(parameters, KeyContainerPermissionFlags.Open | KeyContainerPermissionFlags.Sign);
                kp.AccessEntries.Add(entry);
                kp.Demand();
            }

            if (m_safeCryptMsgHandle == null || m_safeCryptMsgHandle.IsInvalid)
            {
                // First signer.
                Sign(signer, silent);
            }
            else
            {
                // Co-signing.
                CoSign(signer, silent);
            }
        }
Esempio n. 25
0
        internal XmlElement GetXml(XmlDocument document)
        {
            // Create the EncryptedKey element
            XmlElement encryptedKeyElement = (XmlElement)document.CreateElement("EncryptedKey", EncryptedXml.XmlEncNamespaceUrl);

            // Deal with attributes
            if (!String.IsNullOrEmpty(this.Id))
            {
                encryptedKeyElement.SetAttribute("Id", this.Id);
            }
            if (!String.IsNullOrEmpty(this.Type))
            {
                encryptedKeyElement.SetAttribute("Type", this.Type);
            }
            if (!String.IsNullOrEmpty(this.MimeType))
            {
                encryptedKeyElement.SetAttribute("MimeType", this.MimeType);
            }
            if (!String.IsNullOrEmpty(this.Encoding))
            {
                encryptedKeyElement.SetAttribute("Encoding", this.Encoding);
            }
            if (!String.IsNullOrEmpty(this.Recipient))
            {
                encryptedKeyElement.SetAttribute("Recipient", this.Recipient);
            }

            // EncryptionMethod
            if (this.EncryptionMethod != null)
            {
                encryptedKeyElement.AppendChild(this.EncryptionMethod.GetXml(document));
            }

            // KeyInfo
            if (this.KeyInfo.Count > 0)
            {
                encryptedKeyElement.AppendChild(this.KeyInfo.GetXml(document));
            }

            // CipherData
            if (this.CipherData == null)
            {
                throw new CryptographicException(SecurityResources.GetResourceString("Cryptography_Xml_MissingCipherData"));
            }
            encryptedKeyElement.AppendChild(this.CipherData.GetXml(document));

            // EncryptionProperties
            if (this.EncryptionProperties.Count > 0)
            {
                XmlElement encryptionPropertiesElement = document.CreateElement("EncryptionProperties", EncryptedXml.XmlEncNamespaceUrl);
                for (int index = 0; index < this.EncryptionProperties.Count; index++)
                {
                    EncryptionProperty ep = this.EncryptionProperties.Item(index);
                    encryptionPropertiesElement.AppendChild(ep.GetXml(document));
                }
                encryptedKeyElement.AppendChild(encryptionPropertiesElement);
            }

            // ReferenceList
            if (this.ReferenceList.Count > 0)
            {
                XmlElement referenceListElement = document.CreateElement("ReferenceList", EncryptedXml.XmlEncNamespaceUrl);
                for (int index = 0; index < this.ReferenceList.Count; index++)
                {
                    referenceListElement.AppendChild(this.ReferenceList[index].GetXml(document));
                }
                encryptedKeyElement.AppendChild(referenceListElement);
            }

            // CarriedKeyName
            if (this.CarriedKeyName != null)
            {
                XmlElement carriedKeyNameElement = (XmlElement)document.CreateElement("CarriedKeyName", EncryptedXml.XmlEncNamespaceUrl);
                XmlText    carriedKeyNameText    = document.CreateTextNode(this.CarriedKeyName);
                carriedKeyNameElement.AppendChild(carriedKeyNameText);
                encryptedKeyElement.AppendChild(carriedKeyNameElement);
            }

            return(encryptedKeyElement);
        }
Esempio n. 26
0
        /// <include file='doc\Signature.uex' path='docs/doc[@for="Signature.LoadXml"]/*' />
        public void LoadXml(XmlElement value)
        {
            // Make sure we don't get passed null
            if (value == null)
            {
                throw new ArgumentNullException("value");
            }

            // Signature
            XmlElement signatureElement = value;

            if (!signatureElement.LocalName.Equals("Signature"))
            {
                throw new CryptographicException(SecurityResources.GetResourceString("Cryptography_Xml_InvalidElement"), "Signature");
            }

            XmlAttributeCollection signatureAttributes = signatureElement.Attributes;
            XmlNode idAttribute = signatureAttributes["Id"];

            if (idAttribute == null)
            {
                m_strId = null;
            }
            //throw new CryptographicException(String.Format(Environment.GetResourceString("Cryptography_XML_MalformedXML"),"Signature"));

            // Look for SignedInfo and SignatureValue. There may optionally be
            // a KeyInfo and some Objects

            XmlNamespaceManager nsm = new XmlNamespaceManager(value.OwnerDocument.NameTable);

            nsm.AddNamespace("ds", SignedXml.XmlDsigNamespaceUrl);

            // SignedInfo
            //XmlNodeList signatureChilds = signatureElement.GetElementsByTagName("SignedInfo", SignedXml.XmlDsigNamespaceUrl);
            XmlNodeList signatureChilds = signatureElement.SelectNodes("ds:SignedInfo", nsm);

            if (signatureChilds.Count == 0)
            {
                throw new CryptographicException(SecurityResources.GetResourceString("Cryptography_Xml_InvalidElement"), "SignedInfo");
            }
            XmlElement signedInfoElement = (XmlElement)signatureChilds.Item(0);

            m_signedInfo = new SignedInfo();
            m_signedInfo.LoadXml(signedInfoElement);

            // SignatureValue
            XmlNodeList signatureValueNodes = signatureElement.SelectNodes("ds:SignatureValue", nsm);

            if (signatureValueNodes.Count == 0)
            {
                throw new CryptographicException(SecurityResources.GetResourceString("Cryptography_Xml_InvalidElement"), "SignedInfo/SignatureValue");
            }
            XmlElement signatureValueElement = (XmlElement)signatureValueNodes.Item(0);

            m_rgbSignatureValue = Convert.FromBase64String(SignedXml.DiscardWhiteSpaces(signatureValueElement.InnerText));

            XmlNodeList keyInfoNodes = signatureElement.SelectNodes("ds:KeyInfo", nsm);

            if (keyInfoNodes.Count != 0)
            {
                XmlElement keyInfoElement = (XmlElement)keyInfoNodes.Item(0);
                m_keyInfo = new KeyInfo();
                m_keyInfo.LoadXml(keyInfoElement);
            }

            XmlNodeList objectNodes = signatureElement.SelectNodes("ds:Object", nsm);

            for (int i = 0; i < objectNodes.Count; ++i)
            {
                XmlElement objectElement = (XmlElement)objectNodes.Item(i);
                DataObject dataObj       = new DataObject();
                dataObj.LoadXml(objectElement);
                m_embeddedObjects.Add(dataObj);
            }

            // Select all elements that have Id attributes
            XmlNodeList nodeList = signatureElement.SelectNodes("//*[@Id]", nsm);

            if (nodeList != null)
            {
                foreach (XmlNode node in nodeList)
                {
                    m_referencedItems.Add(node);
                }
            }
        }
Esempio n. 27
0
        public int Add(CryptographicAttributeObject attribute)
        {
            if (attribute == null)
            {
                throw new ArgumentNullException("attribute");
            }

            //
            // Merge with exisitng attribute, if already existed, else add as new.
            //

            string szOid1 = null;

            if (attribute.Oid != null)
            {
                szOid1 = attribute.Oid.Value;
            }

            for (int index = 0; index < m_list.Count; index++)
            {
                CryptographicAttributeObject existing = (CryptographicAttributeObject)m_list[index];

                // To prevent caller to add the existing item into the collection again
                // Otherwise the merge will be an infinite loop
                if ((Object)existing.Values == (Object)attribute.Values)
                {
                    throw new InvalidOperationException(SecurityResources.GetResourceString("InvalidOperation_DuplicateItemNotAllowed"));
                }

                // Merge either:
                // 1. both OIDs are null, or
                // 2. both not null and OIDs match.
                string szOid2 = null;
                if (existing.Oid != null)
                {
                    szOid2 = existing.Oid.Value;
                }

                if (szOid1 == null && szOid2 == null)
                {
                    foreach (AsnEncodedData asnEncodedData in attribute.Values)
                    {
                        existing.Values.Add(asnEncodedData);
                    }
                    return(index);
                }

                if ((szOid1 != null && szOid2 != null) && (String.Compare(szOid1, szOid2, StringComparison.OrdinalIgnoreCase) == 0))
                {
                    //
                    // Only allow one signing time, per RFC.
                    //

                    if (String.Compare(szOid1, CAPI.szOID_RSA_signingTime, StringComparison.OrdinalIgnoreCase) == 0)
                    {
                        throw new CryptographicException(SecurityResources.GetResourceString("Cryptography_Pkcs9_MultipleSigningTimeNotAllowed"));
                    }

                    foreach (AsnEncodedData asnEncodedData in attribute.Values)
                    {
                        existing.Values.Add(asnEncodedData);
                    }
                    return(index);
                }
            }

            return(m_list.Add(attribute));
        }
Esempio n. 28
0
        public void LoadXml(XmlElement value)
        {
            // Make sure we don't get passed null
            if (value == null)
            {
                throw new ArgumentNullException("value");
            }

            // Signature
            XmlElement signatureElement = value;

            if (!signatureElement.LocalName.Equals("Signature"))
            {
                throw new CryptographicException(SecurityResources.GetResourceString("Cryptography_Xml_InvalidElement"), "Signature");
            }

            // Attributes
            m_id = Utils.GetAttribute(signatureElement, "Id", SignedXml.XmlDsigNamespaceUrl);
            if (!Utils.VerifyAttributes(signatureElement, "Id"))
            {
                throw new CryptographicException(SecurityResources.GetResourceString("Cryptography_Xml_InvalidElement"), "Signature");
            }

            XmlNamespaceManager nsm = new XmlNamespaceManager(value.OwnerDocument.NameTable);

            nsm.AddNamespace("ds", SignedXml.XmlDsigNamespaceUrl);
            int expectedChildNodes = 0;

            // SignedInfo
            XmlNodeList signedInfoNodes = signatureElement.SelectNodes("ds:SignedInfo", nsm);

            if (signedInfoNodes == null || signedInfoNodes.Count == 0 || (!Utils.GetAllowAdditionalSignatureNodes() && signedInfoNodes.Count > 1))
            {
                throw new CryptographicException(SecurityResources.GetResourceString("Cryptography_Xml_InvalidElement"), "SignedInfo");
            }
            XmlElement signedInfoElement = signedInfoNodes[0] as XmlElement;

            expectedChildNodes += signedInfoNodes.Count;

            this.SignedInfo = new SignedInfo();
            this.SignedInfo.LoadXml(signedInfoElement);

            // SignatureValue
            XmlNodeList signatureValueNodes = signatureElement.SelectNodes("ds:SignatureValue", nsm);

            if (signatureValueNodes == null || signatureValueNodes.Count == 0 || (!Utils.GetAllowAdditionalSignatureNodes() && signatureValueNodes.Count > 1))
            {
                throw new CryptographicException(SecurityResources.GetResourceString("Cryptography_Xml_InvalidElement"), "SignatureValue");
            }
            XmlElement signatureValueElement = signatureValueNodes[0] as XmlElement;

            expectedChildNodes += signatureValueNodes.Count;
            m_signatureValue    = Convert.FromBase64String(Utils.DiscardWhiteSpaces(signatureValueElement.InnerText));
            m_signatureValueId  = Utils.GetAttribute(signatureValueElement, "Id", SignedXml.XmlDsigNamespaceUrl);
            if (!Utils.VerifyAttributes(signatureValueElement, "Id"))
            {
                throw new CryptographicException(SecurityResources.GetResourceString("Cryptography_Xml_InvalidElement"), "SignatureValue");
            }

            // KeyInfo - optional single element
            XmlNodeList keyInfoNodes = signatureElement.SelectNodes("ds:KeyInfo", nsm);

            m_keyInfo = new KeyInfo();
            if (keyInfoNodes != null)
            {
                if (!Utils.GetAllowAdditionalSignatureNodes() && keyInfoNodes.Count > 1)
                {
                    throw new CryptographicException(SecurityResources.GetResourceString("Cryptography_Xml_InvalidElement"), "KeyInfo");
                }
                foreach (XmlNode node in keyInfoNodes)
                {
                    XmlElement keyInfoElement = node as XmlElement;
                    if (keyInfoElement != null)
                    {
                        m_keyInfo.LoadXml(keyInfoElement);
                    }
                }
                expectedChildNodes += keyInfoNodes.Count;
            }

            // Object - zero or more elements allowed
            XmlNodeList objectNodes = signatureElement.SelectNodes("ds:Object", nsm);

            m_embeddedObjects.Clear();
            if (objectNodes != null)
            {
                foreach (XmlNode node in objectNodes)
                {
                    XmlElement objectElement = node as XmlElement;
                    if (objectElement != null)
                    {
                        DataObject dataObj = new DataObject();
                        dataObj.LoadXml(objectElement);
                        m_embeddedObjects.Add(dataObj);
                    }
                }
                expectedChildNodes += objectNodes.Count;
            }

            // Select all elements that have Id attributes
            XmlNodeList nodeList = signatureElement.SelectNodes("//*[@Id]", nsm);

            if (nodeList != null)
            {
                foreach (XmlNode node in nodeList)
                {
                    m_referencedItems.Add(node);
                }
            }

            // Verify that there aren't any extra nodes that aren't allowed
            if (!Utils.GetAllowAdditionalSignatureNodes() && (signatureElement.SelectNodes("*").Count != expectedChildNodes))
            {
                throw new CryptographicException(SecurityResources.GetResourceString("Cryptography_Xml_InvalidElement"), "Signature");
            }
        }
        public void ComputeSignature(KeyedHashAlgorithm macAlg)
        {
            int hashSize;

            if (macAlg == null)
            {
                throw new ArgumentNullException("macAlg");
            }
            HMAC hash = macAlg as HMAC;

            if (hash == null)
            {
                throw new CryptographicException(SecurityResources.GetResourceString("Cryptography_Xml_SignatureMethodKeyMismatch"));
            }
            if (this.m_signature.SignedInfo.SignatureLength == null)
            {
                hashSize = hash.HashSize;
            }
            else
            {
                hashSize = Convert.ToInt32(this.m_signature.SignedInfo.SignatureLength, (IFormatProvider)null);
            }
            if ((hashSize < 0) || (hashSize > hash.HashSize))
            {
                throw new CryptographicException(SecurityResources.GetResourceString("Cryptography_Xml_InvalidSignatureLength"));
            }
            if ((hashSize % 8) != 0)
            {
                throw new CryptographicException(SecurityResources.GetResourceString("Cryptography_Xml_InvalidSignatureLength2"));
            }
            this.BuildDigestedReferences();
            switch (hash.HashName)
            {
            case "SHA1":
                this.SignedInfo.SignatureMethod = "http://www.w3.org/2000/09/xmldsig#hmac-sha1";
                break;

            case "SHA256":
                this.SignedInfo.SignatureMethod = "http://www.w3.org/2001/04/xmldsig-more#hmac-sha256";
                break;

            case "SHA384":
                this.SignedInfo.SignatureMethod = "http://www.w3.org/2001/04/xmldsig-more#hmac-sha384";
                break;

            case "SHA512":
                this.SignedInfo.SignatureMethod = "http://www.w3.org/2001/04/xmldsig-more#hmac-sha512";
                break;

            case "MD5":
                this.SignedInfo.SignatureMethod = "http://www.w3.org/2001/04/xmldsig-more#hmac-md5";
                break;

            case "RIPEMD160":
                this.SignedInfo.SignatureMethod = "http://www.w3.org/2001/04/xmldsig-more#hmac-ripemd160";
                break;

            default:
                throw new CryptographicException(SecurityResources.GetResourceString("Cryptography_Xml_SignatureMethodKeyMismatch"));
            }
            byte[] src = this.GetC14NDigest(hash);
            SignedXmlDebugLog.LogSigning(this, hash);
            this.m_signature.SignatureValue = new byte[hashSize / 8];
            Buffer.BlockCopy(src, 0, this.m_signature.SignatureValue, 0, hashSize / 8);
        }
        public override void LoadXml(XmlElement value)
        {
            if (value == null)
            {
                throw new ArgumentNullException("value");
            }
            XmlNamespaceManager nsmgr = new XmlNamespaceManager(value.OwnerDocument.NameTable);

            nsmgr.AddNamespace("enc", "http://www.w3.org/2001/04/xmlenc#");
            nsmgr.AddNamespace("ds", "http://www.w3.org/2000/09/xmldsig#");
            this.Id        = System.Security.Cryptography.Xml.Utils.GetAttribute(value, "Id", "http://www.w3.org/2001/04/xmlenc#");
            this.Type      = System.Security.Cryptography.Xml.Utils.GetAttribute(value, "Type", "http://www.w3.org/2001/04/xmlenc#");
            this.MimeType  = System.Security.Cryptography.Xml.Utils.GetAttribute(value, "MimeType", "http://www.w3.org/2001/04/xmlenc#");
            this.Encoding  = System.Security.Cryptography.Xml.Utils.GetAttribute(value, "Encoding", "http://www.w3.org/2001/04/xmlenc#");
            this.Recipient = System.Security.Cryptography.Xml.Utils.GetAttribute(value, "Recipient", "http://www.w3.org/2001/04/xmlenc#");
            XmlNode node = value.SelectSingleNode("enc:EncryptionMethod", nsmgr);

            this.EncryptionMethod = new EncryptionMethod();
            if (node != null)
            {
                this.EncryptionMethod.LoadXml(node as XmlElement);
            }
            base.KeyInfo = new KeyInfo();
            XmlNode node2 = value.SelectSingleNode("ds:KeyInfo", nsmgr);

            if (node2 != null)
            {
                base.KeyInfo.LoadXml(node2 as XmlElement);
            }
            XmlNode node3 = value.SelectSingleNode("enc:CipherData", nsmgr);

            if (node3 == null)
            {
                throw new CryptographicException(SecurityResources.GetResourceString("Cryptography_Xml_MissingCipherData"));
            }
            this.CipherData = new CipherData();
            this.CipherData.LoadXml(node3 as XmlElement);
            XmlNode node4 = value.SelectSingleNode("enc:EncryptionProperties", nsmgr);

            if (node4 != null)
            {
                XmlNodeList list = node4.SelectNodes("enc:EncryptionProperty", nsmgr);
                if (list != null)
                {
                    foreach (XmlNode node5 in list)
                    {
                        EncryptionProperty property = new EncryptionProperty();
                        property.LoadXml(node5 as XmlElement);
                        this.EncryptionProperties.Add(property);
                    }
                }
            }
            XmlNode node6 = value.SelectSingleNode("enc:CarriedKeyName", nsmgr);

            if (node6 != null)
            {
                this.CarriedKeyName = node6.InnerText;
            }
            XmlNode node7 = value.SelectSingleNode("enc:ReferenceList", nsmgr);

            if (node7 != null)
            {
                XmlNodeList list2 = node7.SelectNodes("enc:DataReference", nsmgr);
                if (list2 != null)
                {
                    foreach (XmlNode node8 in list2)
                    {
                        DataReference reference = new DataReference();
                        reference.LoadXml(node8 as XmlElement);
                        this.ReferenceList.Add(reference);
                    }
                }
                XmlNodeList list3 = node7.SelectNodes("enc:KeyReference", nsmgr);
                if (list3 != null)
                {
                    foreach (XmlNode node9 in list3)
                    {
                        KeyReference reference2 = new KeyReference();
                        reference2.LoadXml(node9 as XmlElement);
                        this.ReferenceList.Add(reference2);
                    }
                }
            }
            base.m_cachedXml = value;
        }