/// <summary>
        /// Encrypts a list of elements.
        /// </summary>
        /// <param name="elementToAddEncKeysTo"></param>
        /// <param name="elementsToEncrypt"></param>
        /// <param name="certificates"></param>
        /// <param name="cipherKey"></param>
        public void Encrypt(XmlElement elementToAddEncKeysTo,
                            IList <XmlElement> elementsToEncrypt,
                            X509Certificate2Collection certificates, byte[] cipherKey)
        {
            ArgumentUtils.CheckNotNull(elementToAddEncKeysTo, "elementToAddEncKeysTo");
            ArgumentUtils.CheckNotNullNorEmpty(elementsToEncrypt, "elementsToEncrypt");
            CertificateUtils.CheckNotNullOrEmpty(certificates, "certificates");

            // Check all the elements to encrypt are not the same as the element
            // to add the keys to and check they belong to the same document.
            foreach (XmlElement elementToEncrypt in elementsToEncrypt)
            {
                if (elementToEncrypt == elementToAddEncKeysTo)
                {
                    throw new XspException(
                              "Cannot add keys to an element that is being encrypted");
                }

                if (elementToAddEncKeysTo.OwnerDocument !=
                    elementToEncrypt.OwnerDocument)
                {
                    throw new XspException(
                              "Elements to encrypt must belong to the same document as the " +
                              "keys element");
                }

                if (XmlUtils.IsDescendant(elementToEncrypt, elementToAddEncKeysTo))
                {
                    throw new XspException(
                              "Element the keys are added to cannot be a child element of an " +
                              "element to encrypt");
                }
            }

            // Get the container document
            XmlDocument containerDoc = elementToAddEncKeysTo.OwnerDocument;

            // Create a random session key
            RijndaelManaged sessionKey = new RijndaelManaged();

            sessionKey.KeySize = 256;

            if (cipherKey != null)
            {
                sessionKey.Key = cipherKey;
            }

            IList <string> referenceIdList = new List <string>();

            foreach (XmlElement elementToEncrypt in elementsToEncrypt)
            {
                // Generate a unique reference identifier
                string referenceId = "_" + Guid.NewGuid().ToString();

                // Add it to the reference list
                referenceIdList.Add(referenceId);

                // Create the encrypted data
                EncryptedData encryptedData = XmlSecurityUtils.Encrypt(
                    sessionKey, elementToEncrypt, referenceId);

                // Replace the original element with the encrypted data
                EncryptedXml.ReplaceElement(elementToEncrypt, encryptedData, false);
            }

            foreach (X509Certificate2 certificate in certificates)
            {
                // Create the encrypted key
                EncryptedKey encryptedKey = XmlSecurityUtils.CreateEncryptedKey(
                    sessionKey, certificate, referenceIdList);

                // Import the encrypted key element into the container document
                XmlNode encryptedKeyElem =
                    containerDoc.ImportNode(encryptedKey.GetXml(), true);

                elementToAddEncKeysTo.AppendChild(encryptedKeyElem);
            }
        }
        /// <summary>
        /// Decrypts a list of elements.
        /// </summary>
        /// <param name="encryptedKeyElems">List of encrypted key elements.</param>
        /// <param name="encryptedDataElems">List of encrypted data elements.</param>
        /// <param name="certificate">Certificate to use for key decryption.</param>
        public void Decrypt(IList <XmlElement> encryptedKeyElems,
                            IList <XmlElement> encryptedDataElems, X509Certificate2 certificate)
        {
            ArgumentUtils.CheckNotNullNorEmpty(encryptedKeyElems,
                                               "encryptedKeyElems");
            ArgumentUtils.CheckNotNullNorEmpty(encryptedDataElems,
                                               "encryptedDataElems");
            ArgumentUtils.CheckNotNull(certificate, "certificate");

            // Check the certificate has a private key
            if (certificate.PrivateKey == null)
            {
                throw new XspException("Certificate with subject '" +
                                       certificate.Subject + "' does not contain a private key");
            }

            XmlDocument containerDoc = encryptedKeyElems[0].OwnerDocument;

            // Check the 'encryptedKeyElems' elements
            foreach (XmlElement encryptedKeyElem in encryptedKeyElems)
            {
                // Check they are all 'xenc:EncryptedKey' elements
                if (!XmlUtils.CheckElement(encryptedKeyElem, EncryptedKeyTag,
                                           EncryptedXml.XmlEncNamespaceUrl))
                {
                    throw new XspException("Element within the keys list is not " +
                                           "an 'xenc:EncryptedKey'");
                }

                // Check they all belong to the same document
                if (encryptedKeyElem.OwnerDocument != containerDoc)
                {
                    throw new XspException("All 'xenc:EncryptedKey' elements " +
                                           "must belong to the same document");
                }
            }

            // Check the 'encryptedDataElems' elements
            foreach (XmlElement encryptedDataElem in encryptedDataElems)
            {
                // Check they are all 'xenc:EncryptedData' elements
                if (!XmlUtils.CheckElement(encryptedDataElem, EncryptedDataTag,
                                           EncryptedXml.XmlEncNamespaceUrl))
                {
                    throw new XspException("Element within the encrypted data list is " +
                                           "not an 'xenc:EncryptedData' element.");
                }

                // Check they all belong to the same document
                if (encryptedDataElem.OwnerDocument != containerDoc)
                {
                    throw new XspException("All 'xenc:EncryptedData' elements " +
                                           "must belong to the same document");
                }
            }

            // Attempt to find the matching encrypted key for the certificate
            EncryptedKey encryptedKey = null;

            foreach (XmlElement encryptedKeyElem in encryptedKeyElems)
            {
                EncryptedKey currentEncryptedKey = new EncryptedKey();
                currentEncryptedKey.LoadXml(encryptedKeyElem);

                // Check if the subject key identifier specified within the
                // 'KeyInfo' of the encrypted key matches the certificate
                if (MatchesCertificate(currentEncryptedKey, certificate))
                {
                    encryptedKey = currentEncryptedKey;
                    break;
                }
            }

            // Check if a key was found
            if (encryptedKey == null)
            {
                throw new KeyMismatchException(
                          "Could not find a matching encrypted key for certificate '" +
                          certificate.Subject + "'.");
            }

            // Decrypt the encrypted key
            RijndaelManaged sessionKey = new RijndaelManaged();

            sessionKey.Key = XmlSecurityUtils.DecryptEncryptedKey(
                encryptedKey, certificate.PrivateKey);

            // Decrypt each of the encrypted data elements using the decrypted key
            foreach (XmlElement encryptedDataElem in encryptedDataElems)
            {
                // Decrypt the data
                byte[] decryptedData = XmlSecurityUtils.Decrypt(
                    encryptedDataElem, sessionKey);

                // Replace the encrypted data with the decrypted data within the container
                EncryptedXml encryptedXml = new EncryptedXml(containerDoc);
                encryptedXml.ReplaceData(encryptedDataElem, decryptedData);
            }
        }
Example #3
0
        /// <summary>
        /// Writes the response file for <c>midl.exe</c>.
        /// </summary>
        private void WriteResponseFile(TextWriter writer)
        {
            // suppresses display of the sign-on banner
            writer.WriteLine("/nologo");

            writer.WriteLine("/env " + _env);

            if (_acf != null)
            {
                writer.WriteLine("/acf {0}", _acf);
            }
            if (_align != null)
            {
                writer.WriteLine("/align {0}", _align);
            }
            if (_appConfig)
            {
                writer.WriteLine("/app_config");
            }
            if (_char != null)
            {
                writer.WriteLine("/char {0}", _char);
            }
            if (_client != null)
            {
                writer.WriteLine("/client {0}", _client);
            }
            if (_cstub != null)
            {
                writer.WriteLine("/cstub {0}", _cstub);
            }
            if (_dlldata != null)
            {
                writer.WriteLine("/dlldata \"{0}\"", DllData.FullName);
            }
            if (_Oi != null)
            {
                writer.WriteLine("/Oi" + _Oi);
            }
            if (Tlb != null)
            {
                writer.WriteLine("/tlb \"{0}\"", Tlb.FullName);
            }
            if (_header != null)
            {
                writer.WriteLine("/header \"{0}\"", Header.FullName);
            }
            if (Iid != null)
            {
                writer.WriteLine("/iid \"{0}\"", Iid.FullName);
            }
            if (Proxy != null)
            {
                writer.WriteLine("/proxy \"{0}\"", Proxy.FullName);
            }

            foreach (Option define in Defines)
            {
                if (!define.IfDefined || define.UnlessDefined)
                {
                    continue;
                }

                if (define.Value == null)
                {
                    writer.WriteLine("/D " + ArgumentUtils.FixTrailingBackslash(define.OptionName));
                }
                else
                {
                    writer.WriteLine("/D " + define.OptionName + "=" + ArgumentUtils.FixTrailingBackslash(define.Value));
                }
            }

            foreach (Option undefine in Undefines)
            {
                if (!undefine.IfDefined || undefine.UnlessDefined)
                {
                    continue;
                }

                writer.WriteLine("/U " + ArgumentUtils.QuoteArgumentValue(
                                     undefine.OptionName, BackslashProcessingMethod.Fix));
            }

            foreach (Option option in _options)
            {
                if (IfDefined && !UnlessDefined)
                {
                    if (option.Value == null)
                    {
                        writer.WriteLine(option.OptionName);
                    }
                    else
                    {
                        writer.WriteLine(option.OptionName + " " + option.Value);
                    }
                }
            }

            // append user provided include directories
            foreach (string include in IncludeDirs.DirectoryNames)
            {
                writer.WriteLine("/I {0}", ArgumentUtils.QuoteArgumentValue(
                                     include, BackslashProcessingMethod.Clean));
            }

            writer.WriteLine("\"{0}\"", Filename.FullName);
        }
Example #4
0
 /// <summary>
 /// Quotes an argument value and duplicates trailing backslahes.
 /// </summary>
 /// <param name="value">The argument value to quote.</param>
 /// <returns>
 /// The quotes argument value.
 /// </returns>
 public static string QuoteArgumentValue(string value)
 {
     return(ArgumentUtils.QuoteArgumentValue(value,
                                             BackslashProcessingMethod.Duplicate));
 }
        /// <summary>
        /// Creates a new instance of the <see cref="DS.AFP.Communication.IO.StreamResource"/> class.
        /// </summary>
        /// <param name="stream">The <see cref="System.IO.Stream"/> to use.</param>
        public StreamResource(Stream stream)
        {
            ArgumentUtils.AssertNotNull(stream, "stream");

            this.stream = stream;
        }
Example #6
0
        /// <summary>
        /// Creates the library.
        /// </summary>
        protected override void ExecuteTask()
        {
            // ensure base directory is set, even if fileset was not initialized
            // from XML
            if (Sources.BaseDirectory == null)
            {
                Sources.BaseDirectory = new DirectoryInfo(Project.BaseDirectory);
            }
            if (LibDirs.BaseDirectory == null)
            {
                LibDirs.BaseDirectory = new DirectoryInfo(Project.BaseDirectory);
            }

            if (!NeedsCompiling())
            {
                return;
            }

            Log(Level.Info, "Combining {0} files to '{1}'.",
                Sources.FileNames.Count, OutputFile.FullName);

            // Create temp response file to hold compiler options
            _responseFileName = Path.GetTempFileName();
            StreamWriter writer = new StreamWriter(_responseFileName);

            try {
                // specify the output file
                writer.WriteLine("/OUT:\"{0}\"", OutputFile.FullName);

                // write user provided options
                if (Options != null)
                {
                    writer.WriteLine(Options);
                }

                // write each of the filenames
                foreach (string filename in Sources.FileNames)
                {
                    writer.WriteLine(ArgumentUtils.QuoteArgumentValue(filename,
                                                                      BackslashProcessingMethod.None));
                }

                // write symbols
                foreach (Symbol symbol in Symbols)
                {
                    if (symbol.IfDefined && !symbol.UnlessDefined)
                    {
                        writer.WriteLine("/INCLUDE:{0}", ArgumentUtils.QuoteArgumentValue(
                                             symbol.SymbolName, BackslashProcessingMethod.Duplicate));
                    }
                }

                // names of default libraries to ignore
                foreach (Library ignoreLibrary in IgnoreLibraries)
                {
                    if (ignoreLibrary.IfDefined && !ignoreLibrary.UnlessDefined)
                    {
                        writer.WriteLine("/NODEFAULTLIB:{0}", ArgumentUtils.QuoteArgumentValue(
                                             ignoreLibrary.LibraryName, BackslashProcessingMethod.Duplicate));
                    }
                }

                // write each of the libdirs
                foreach (string libdir in LibDirs.DirectoryNames)
                {
                    writer.WriteLine("/LIBPATH:{0}", ArgumentUtils.QuoteArgumentValue(
                                         libdir, BackslashProcessingMethod.None));
                }

                if (ModuleDefinitionFile != null)
                {
                    writer.WriteLine("/DEF:\"{0}\"", ModuleDefinitionFile.FullName);
                }

                // suppresses display of the sign-on banner
                writer.WriteLine("/nologo");

                writer.Close();

                if (Verbose)
                {
                    // display response file contents
                    Log(Level.Info, "Contents of {0}.", _responseFileName);
                    StreamReader reader = File.OpenText(_responseFileName);
                    Log(Level.Info, reader.ReadToEnd());
                    reader.Close();
                }

                // call base class to do the actual work
                base.ExecuteTask();
            } finally {
                // make sure we delete response file even if an exception is thrown
                writer.Close(); // make sure stream is closed or file cannot be deleted
                File.Delete(_responseFileName);
                _responseFileName = null;
            }
        }
        private static double ToLon(double x, int zoomLevel)
        {
            var zoomFactor = K * Math.Pow(2, zoomLevel);

            return(ArgumentUtils.ToDegrees(x / zoomFactor - Math.PI));
        }
        private static double ToLat(double y, int zoomLevel)
        {
            var zoomFactor = K * Math.Pow(2, zoomLevel);

            return(ArgumentUtils.ToDegrees(2 * (Math.Atan(Math.Exp(Math.PI - y / zoomFactor)) - Math.PI / 4)));
        }
        private static double ToY(double latitude, int zoomLevel)
        {
            var zoomFactor = K * Math.Pow(2, zoomLevel);

            return(zoomFactor * (Math.PI - Math.Log(Math.Tan(Math.PI / 4 + ArgumentUtils.ToRadians(latitude) / 2))));
        }
Example #10
0
        private static double ToX(double longitude, int zoomLevel)
        {
            var zoomFactor = K * Math.Pow(2, zoomLevel);

            return(zoomFactor * (ArgumentUtils.ToRadians(longitude) + Math.PI));
        }
Example #11
0
 public void EscapeQuotes()
 {
     Assert.AreEqual(new string[] { "/D" },
                     ArgumentUtils.FixupArgs(new string[] { "/D" }));
 }
Example #12
0
 public void EscapeSlashes()
 {
     Assert.AreEqual("foo\\bar\\file.c",
                     ArgumentUtils.JoinAguments(new string[] { "foo\\bar\\file.c" }));
 }
Example #13
0
        /// <summary>
        /// Compiles the sources.
        /// </summary>
        protected override void ExecuteTask() {
            // ensure base directory is set, even if fileset was not initialized
            // from XML
            if (Sources.BaseDirectory == null) {
                Sources.BaseDirectory = new DirectoryInfo(Project.BaseDirectory);
            }
            if (IncludeDirs.BaseDirectory == null) {
                IncludeDirs.BaseDirectory = new DirectoryInfo(Project.BaseDirectory);
            }
            if (MetaDataIncludeDirs.BaseDirectory == null) {
                MetaDataIncludeDirs.BaseDirectory = new DirectoryInfo(Project.BaseDirectory);
            }
            if (ForcedUsingFiles.BaseDirectory == null) {
                ForcedUsingFiles.BaseDirectory = new DirectoryInfo(Project.BaseDirectory);
            }

            if (NeedsCompiling()) {
                Log(Level.Info, "Compiling {0} files to '{1}'.", 
                    _dirtySources.Count, OutputDir.FullName);
 
                // create temp response file to hold compiler options
                _responseFileName = Path.GetTempFileName();
                StreamWriter writer = new StreamWriter(_responseFileName);
 
                try {
                    // write basic switches
                    writer.WriteLine("/c"); // compile only

                    if (Options != null) {
                        // write user defined options
                        writer.WriteLine(Options);
                    }

                    if (ManagedExtensions) {
                        // enables Managed Extensions for C++
                        writer.WriteLine("/clr");
                    }

                    // write preprocesser define(s)
                    foreach (Option define in Defines) {
                        if (!define.IfDefined || define.UnlessDefined) {
                            continue;
                        }

                        if (define.Value == null)  {
                            writer.WriteLine("/D " + QuoteArgumentValue(define.OptionName));
                        } else {
                            writer.WriteLine("/D " + QuoteArgumentValue(define.OptionName 
                                + "=" + ArgumentUtils.DuplicateTrailingBackslash(define.Value)));
                        }
                    }

                    // write preprocesser undefine(s)
                    foreach (Option undefine in Undefines) {
                        if (!undefine.IfDefined || undefine.UnlessDefined) {
                            continue;
                        }

                        writer.WriteLine("/U " + QuoteArgumentValue(undefine.OptionName));
                    }

                    // write user provided include directories
                    foreach (string include in IncludeDirs.DirectoryNames) {
                        writer.WriteLine("/I {0}", QuoteArgumentValue(include));
                    }

                    // write directories that the compiler will search to resolve 
                    // file references passed to the #using directive
                    foreach (string metaDataIncludeDir in MetaDataIncludeDirs.DirectoryNames) {
                        writer.WriteLine("/AI {0}", QuoteArgumentValue(metaDataIncludeDir));
                    }

                    // writes metadata files to reference in this compilation 
                    // as an alternative to passing a file name to #using in 
                    // source code
                    foreach (string forcedUsingFile in ForcedUsingFiles.FileNames) {
                        writer.WriteLine("/FU {0}", QuoteArgumentValue(forcedUsingFile));
                    }

                    // program database file
                    writer.WriteLine("/Fd{0}", QuoteArgumentValue(ProgramDatabaseFile));

                    // the object file or output directory
                    writer.WriteLine("/Fo{0}", QuoteArgumentValue(ObjectFile));

                    // specify pch file, if user specified one
                    if (PchFile != null) {
                        writer.WriteLine("/Fp{0}", QuoteArgumentValue(PchFile));

                        switch (PchMode) {
                            case PrecompiledHeaderMode.Use:
                                writer.Write("/Yu");
                                break;
                            case PrecompiledHeaderMode.Create:
                                writer.Write("/Yc");
                                break;
                            case PrecompiledHeaderMode.AutoCreate:
                                writer.Write("/YX");
                                break;
                        }

                        if (PchThroughFile != null) {
                            writer.WriteLine("{0}", QuoteArgumentValue(PchThroughFile));
                        }
                    }

                    // write each of the filenames
                    foreach (string filename in _dirtySources) {
                        writer.WriteLine(QuoteArgumentValue(filename));
                    }

                    // tell compiler which character set to use
                    switch (CharacterSet) {
                        case CharacterSet.Unicode:
                            writer.WriteLine("/D \"_UNICODE\"");
                            writer.WriteLine("/D \"UNICODE\"");
                            break;
                        case CharacterSet.MultiByte:
                            writer.WriteLine("/D \"_MBCS\"");
                            break;
                    }

                    writer.Close();

                    if (Verbose) {
                        // display response file contents
                        Log(Level.Info, "Contents of {0}.", _responseFileName);
                        StreamReader reader = File.OpenText(_responseFileName);
                        Log(Level.Info, reader.ReadToEnd());
                        reader.Close();
                    }

                    // suppresses display of the sign-on banner
                    // (this has no effect in response file)
                    this.Arguments.Add(new Argument("/nologo"));

                    // call base class to do the actual work
                    base.ExecuteTask();
                } finally {
                    // make sure we delete response file even if an exception is thrown
                    writer.Close(); // make sure stream is closed or file cannot be deleted
                    File.Delete(_responseFileName);
                    _responseFileName = null;
                }
            }
        }