Muralidharan's profileMurali@B'lorePhotosBlogLists Tools Help

Blog


    November 13

    Encrypt & Decrypt XML using C# (2.0)

    using System;
    using System.Collections.Generic;
    using System.Text;
    using System.Security;
    using System.Security.Cryptography;
    using System.Security.Cryptography.Xml;
    using System.Xml;
    namespace XmlEncryption
    {
        class Program
        {
            static void Main(string[] args)
            {
                EncryptionXML(); // Encryption
                DecryptionXML(); // Decryption
            }
            public static void DecryptionXML()
            {
                TripleDESCryptoServiceProvider sharedKey = new TripleDESCryptoServiceProvider();
                System.IO.StreamReader reader = new System.IO.StreamReader("sharedTDESkey.txt");
                Byte[] data = Convert.FromBase64String(reader.ReadToEnd());
                sharedKey.Key = data; //Assign the retrieved shared key value to the TripleDESCryptoServiceProvider object
                XmlDocument encryptedDoc = new XmlDocument();
                encryptedDoc.Load("encryptedorder.xml");
                XmlElement encryptedElement = (XmlElement) encryptedDoc.GetElementsByTagName("EncryptedData")[0];
                EncryptedData ed2 = new EncryptedData();
                ed2.LoadXml(encryptedElement); //Create an EncryptedData object and populate it.
                EncryptedXml exml2 = new EncryptedXml();
                Byte[] decryptedBilling = exml2.DecryptData(ed2, sharedKey); //  Decrypt the element using the shared key
                // Replace the encryptedData element with the plaintext XML element.
                exml2.ReplaceData(encryptedElement, decryptedBilling);
                encryptedDoc.Save("DecryptedOrder.xml");
            }
            public static void EncryptionXML()
            {
                XmlDocument xmldoc = new XmlDocument();
                try
                {
                    xmldoc.Load("order.xml");
                }
                catch (Exception ex)
                {
                    Console.WriteLine(ex.Message);
                    throw;
                }
                //Create a new TripleDES object, TripleDes will be the algorithm used to encrypt the XML data
                TripleDESCryptoServiceProvider sharedkey = new TripleDESCryptoServiceProvider();
                //Save this key to disk to enable the recipient to decrypt
                System.IO.StreamWriter writer2 = new System.IO.StreamWriter("SharedTDESKey.txt");
                String str = Convert.ToBase64String(sharedkey.Key);
                writer2.WriteLine(str);
                writer2.Close();
                //Create a new EncryptedXML object
                EncryptedXml exml = new EncryptedXml(xmldoc);
                //Select the Billing element to be encrypted
                XmlElement billingElem = (XmlElement)xmldoc.SelectSingleNode("/order");
                //Encrypt the billing element data using the TripleDES alogrithm, save the results into a byte array
                Byte[] encryptedBilling = exml.EncryptData(billingElem, sharedkey, false);
                //Create an EncryptedData object and populate it.
                EncryptedData ed = new EncryptedData();
                //Specify the namespace URI for XML encryption elements.
                ed.Type = EncryptedXml.XmlEncElementUrl;
                // Specify the namespace URI for the TrippleDES algorithm.
                ed.EncryptionMethod = new EncryptionMethod(EncryptedXml.XmlEncTripleDESUrl);
                //Create a CipherData element.
                ed.CipherData = new CipherData();
                //Set the CipherData element to the value of the encrypted XML element.
                ed.CipherData.CipherValue = encryptedBilling;
                // Replace the plaintext XML elemnt with an EncryptedData element.
                EncryptedXml.ReplaceElement(billingElem, ed, false);
                //Write the encrypted data to disk
                try
                {
                    xmldoc.Save("encryptedorder.xml");
                }
                catch (Exception ex)
                {
                    Console.WriteLine(ex.Message);
                }
            }
        }
    }

    Introduction to Pragmatic Architecture Series

     
    It's become almost fashionable to poke fun at that group of software engineers that call themselves architects. If you are one of those who call themselves architects, how do you address this rather unenviable state of affairs? Are we nearing extinction?
     
     
     
    November 07

    Windows Communication Foundation with Windows Vista and UAC

    If you log into Windows Vista as anything other than the Built-in Administrator and create a Windows Communication Foundation (WCF) service, running the service will result in the following exception:

    System.ServiceModel.AddressAccessDeniedException: HTTP could not register URL http://+:8080/<...>.  Your process does not have access rights to this namespace (see http://msdn.microsoft.com/library/default.asp?url=/library/en-us/http/http/namespace_reservations_registrations_and_routing.asp for details). ---> System.Net.HttpListenerException: Access is denied

    The issue is User Access Control (UAC), a new feature of Windows Vista that causes processes to run as standard user even if you are logged in with a user that is the member of the Administrators group.  Opening the port for WCF requires administrative access and, unless the process is elevated, no such access is available so opening the port results in the access denied message.

    To handle this error it is necessary to cause a Permit/Deny dialog to appear.  The same dialog appears when running administrative tools like Computer Management.

    Windows Vista Permit/Deny Dialog

    Clicking the Permit button elevates the process, assuming the logged on user has the necessary permissions for the action. 

    One way to turn on the Permit/Deny dialog is to place a manifest into the same directory as the application executable.  The manifest file is named using the full application name (including the EXE extension) with an additional ".MANIFEST" suffix (WCFService.exe.MANIFEST for example).  The content of the file is XML specifying that the application requires administrator permissions so the dialog needs to be displayed to elevate the process.

    <?xml version="1.0" encoding="UTF-8" standalone="yes"?>
    <assembly xmlns="urn:schemas-microsoft-com:asm.v1" manifestVersion="1.0">
      <trustInfo xmlns="urn:schemas-microsoft-com:asm.v3">
        <security>
          <requestedPrivileges>
            <requestedExecutionLevel level="requireAdministrator">
          </requestedPrivileges>
        </security>
      </trustInfo>
    </assembly>

    Note that it is not possible to supply a manifest file to run elevated without the dialog.

    Other ways of avoiding the Access Denied message are:

    1. Turn off UAC by changing the security policy.   Open the Local Security Policy and browse to Security Settings->Local Policies->Security Options' and the User Account Protection options.  Specify all processes run elevated without prompting. 
    2. Increase your security vulnerability and logon as Built-In Administrator.
    3. Launch the WCF Service process in elevated mode (right-click menu option).
    4. Launch the WCF Service from a process, such as Visual Studio or the Command Prompt (MSH), that is running elevated.  Again, right click on the shortcut or executable and select Run Elevated....