Tuesday, April 9, 2013

How to encrypt and decrypt Azure Autoscaling Block Rules Store and Service Information Store in code

The Azure Autoscaling Block (WASABi) has a lot of configurability, but one common way is to store your Rules Store and Service Information Store as xml files and put them up in blob storage. You can also encrypt these XML files and provide the Autoscaling block with the thumbprint of the certificate that was used to encrypt. This is all described in more detail here.

The thing is, I wanted to write a web frontend that would allow authorized users to modify the rules or the service information store as needed. This means at the very least the ability to encrypt and decrypt those files from code. It took me awhile to figure this out, but you can directly access the encryption provider that the Autoscaling Block uses to do this encryption and call its encrypt and decrypt methods. If you write your own provider or use one other than the Pcks12ProtectedXmlProvider included in the Autoscaling Block this won't work, but here is the idea:

        private string EncryptXml(string thumbprint, string xml)
        {
            Microsoft.Practices.EnterpriseLibrary.WindowsAzure.Autoscaling.Security.Pkcs12ProtectedXmlProvider provider = 
                new Microsoft.Practices.EnterpriseLibrary.WindowsAzure.Autoscaling.Security.Pkcs12ProtectedXmlProvider(
                    System.Security.Cryptography.X509Certificates.StoreName.My, System.Security.Cryptography.X509Certificates.StoreLocation.LocalMachine,
                    thumbprint, false);
            XmlDocument doc = new XmlDocument();
            doc.PreserveWhitespace = true;
            doc.Load(new StringReader(xml));

            XmlNode encrypted = provider.Encrypt(doc.DocumentElement);
            return encrypted.OuterXml;
        }

        private string DecryptXml(string thumbprint, string xml)
        {
            Microsoft.Practices.EnterpriseLibrary.WindowsAzure.Autoscaling.Security.Pkcs12ProtectedXmlProvider provider = 
                new Microsoft.Practices.EnterpriseLibrary.WindowsAzure.Autoscaling.Security.Pkcs12ProtectedXmlProvider(
                    System.Security.Cryptography.X509Certificates.StoreName.My, System.Security.Cryptography.X509Certificates.StoreLocation.LocalMachine,
                    thumbprint, false);
            XmlDocument xmlDoc = new XmlDocument();
            xmlDoc.PreserveWhitespace = true;
            xmlDoc.Load(new StringReader(xml));

            XmlNode decryptedNode = provider.Decrypt(xmlDoc.DocumentElement);
            return decryptedNode.OuterXml;
        }

No comments:

Post a Comment