Five New Optimizely Certifications are Here! Validate your expertise and advance your career with our latest certification exams. Click here to find out more

Daniel Ovaska
Jul 13, 2016
  2241
(0 votes)

Episerver Forms–Encrypting submitted data

Background

A nice question that popped up in the forum a couple of days ago is how to encrypt the submitted data in Episerver forms. If you collect sensitive information about your users by using forms, this is definitely a relevant question. You don’t want to be the one who loses your customers personal emails, credit card information etc if someone gets hold of your database. It has happend to plenty of websites unfortunately and it doesn’t build trust with your end users so to speak...

Encrypting the submitted data can be done in a couple of ways and I’ll demonstrate one: extending the default implementation of IPermanentStorage. This can be done easily nowadays (CMS 7+) due to Episerver nifty SOLID architecture. Fun challenge! Let's code!

Step one - Select what elements should be encrypted

First let's create a new attribute to mark what elements we want encrypted. Another option is to use some naming convention or lookup table. I'll go with the attribute this time and create a custom element for it. Let's create a simple TextBox element that uses the attribute.

[ContentType(GUID = "95A98808-4BFC-43FE-B723-4FD2F7E01234")]
[EncryptedFormsElement]
public class EncryptedTextBoxElementBlock : TextboxElementBlock
{
}

public class EncryptedFormsElementAttribute : Attribute
{

}

Now we need a view called EncryptedTextBoxElementBlock.cshtml for the textbox as well to render it.

@using EPiServer.Forms.Core
@using EPiServerSiteV9.Business
@model EPiServerSiteV9.Business.EncryptedTextBoxElementBlock

<div class="Form__Element FormTextbox" data-epiforms-element-name="@Model.FormElement.ElementName">
    <label for="@Model.FormElement.Guid">
        @{
            var label = Model.FormElement.SourceContent.Property["Label"];
        }
        @label
    </label>
    <input type="text" name="@Model.FormElement.ElementName" class="FormTextbox__Input" id="@Model.FormElement.Guid" />


    <span data-epiforms-linked-name="@Model.FormElement.ElementName" class="Form__Element__ValidationError" style="display: none;">*</span>
</div>

Step two - Extend the default implementation of IPermanentStorage

Let's use the default implementation, DdsPermanentStorage, and inherit from that and then extend it with some encryption. This class already takes care of storing everything in DDS for us. Our new implementation uses a simple CryptographyService under the hood to do the heavy lifting with encryption. We need to override both the storing method and the one that gets the data to handle the encryption/decryption. Otherwise editors will find it somewhat problematic to read submissions if we only store it encrypted. The new class also checks whether an element is decorated with the new attribute before it does it's thing.

public class EncryptedFormsDataStorage : DdsPermanentStorage
{
    private readonly ILogger _log = LogManager.GetLogger(typeof(EncryptedFormsDataStorage));
    private readonly ICryptographyService _cryptographyService;
    private Injected<EPiServer.Forms.Core.Data.Internal.DdsStructureStorage> _formStructureStorage;
    private Injected<IContentLoader> _contentLoader;

    public EncryptedFormsDataStorage(ICryptographyService cryptographyService)
    {
        _cryptographyService = cryptographyService;
    }
    public override Guid SaveToStorage(FormIdentity formIden, Submission submission)
    {
        var form = formIden.GetFormBlock();
        var elements = form.ElementsArea.FilteredItems;
        foreach (var contentAreaItem in elements)
        {
            var elementblock = _contentLoader.Service.Get<ElementBlockBase>(contentAreaItem.ContentLink);
            if (ShouldEncryptElement(elementblock))
            {
                var oldText = submission.Data[elementblock.FormElement.ElementName];
                if (oldText != null)
                {
                    submission.Data.Remove(elementblock.FormElement.ElementName);
                    var encryptedText = _cryptographyService.Encrypt(oldText.ToString());
                    submission.Data.Add(elementblock.FormElement.ElementName, encryptedText);
                }
            }
        }
        return base.SaveToStorage(formIden, submission);

    }
    public override IEnumerable<PropertyBag> LoadSubmissionFromStorage(FormIdentity formIden, DateTime beginDate, DateTime endDate, bool finalizeOnly = false)
    {
        try
        {
            var propertyBags = base.LoadSubmissionFromStorage(formIden, beginDate, endDate, finalizeOnly);
            var form = formIden.GetFormBlock();
            var elements = form.ElementsArea.FilteredItems;
            foreach (var contentAreaItem in elements)
            {
                var elementblock = _contentLoader.Service.Get<ElementBlockBase>(contentAreaItem.ContentLink);
                if (ShouldEncryptElement(elementblock))
                {
                    foreach (var propertyBag in propertyBags)
                    {
                        var oldValue = propertyBag[elementblock.FormElement.ElementName];
                        if (oldValue != null)
                        {
                            string newValue;
                            if (_cryptographyService.TryDecrypt(oldValue.ToString(), out newValue))
                            {
                                _log.Information("Decrypted text");
                                propertyBag.Remove(elementblock.FormElement.ElementName);
                                propertyBag.Add(elementblock.FormElement.ElementName, newValue);
                            }
                            else
                            {
                                _log.Error("Failed to decrypt element text");
                            }

                        }

                    }
                }
            }
            return propertyBags;
        }
        catch (Exception ex)
        {
            _log.Error("Error while decrypting", ex);
            throw;
        }
    }
    private bool ShouldEncryptElement(ElementBlockBase element)
    {
        var encryptionAttribute = Attribute.GetCustomAttribute(element.GetType(),
        typeof(EncryptedFormsElementAttribute));
        if (encryptionAttribute == null)
        {
            _log.Information("Element lacks attribute for encryption");
        }
        else
        {
            _log.Information("Element has attribute for encryption");
            return true;
        }
        return false;
    }
}

Step three - Register your implementation

We now need to tell Episerver to use our new implementation of storage for forms. This is done by configuring the structuremap container.

    [InitializableModule]
    [ModuleDependency(typeof(EPiServer.Web.InitializationModule))]
    public class DependencyResolverInitialization : IConfigurableModule
    {
        public void ConfigureContainer(ServiceConfigurationContext context)
        {
            context.Container.Configure(ConfigureContainer);
            DependencyResolver.SetResolver(new StructureMapDependencyResolver(context.Container));
        }

        private static void ConfigureContainer(ConfigurationExpression container)
        {
            container.For<ICryptographyService>().Use<CryptographyService>();
            container.For<IPermanentStorage>().Use<EncryptedFormsDataStorage>();
            ...

Appendix

To wrap it up I'll also include my CryptographyService class. Feel free to change it to use your favorite algorithm.

public interface ICryptographyService
{
    /// <summary>
    /// Array for password salt
    /// </summary>
    byte[] PasswordKeyByteArray { get; set; }

    /// <summary>
    /// Set this to a tough to break string before trying to encrypt
    /// </summary>
    string CryptoKey { get; set; }

    byte[] Encrypt(byte[] clearData, byte[] key, byte[] iv);
    string Encrypt(string clearText);

    /// <summary>
    /// Given wrong key this may cast an exception of type CryptographicException with message "Padding is invalid and cannot be removed"
    /// Decrypt a byte array into a byte array using a key and an IV
    /// Uses Decrypt(byte[], byte[], byte[])
    /// </summary>
    /// <returns></returns>
    byte[] Decrypt(byte[] cipherData,
        byte[] key, byte[] iv);

    /// <summary>
    /// Given wrong key this may cast an exception of type CryptographicException with message "Padding is invalid and cannot be removed"
    /// Decrypt a string into a string using a password
    /// Uses Decrypt(byte[], byte[], byte[])
    /// </summary>
    /// <param name="cipherText"></param>
    /// <returns></returns>
    bool TryDecrypt(string cipherText, out string result);
}

/// <summary>
/// Remember to set crypto key before trying to encrypt / decrypt anything.
/// </summary>
public class CryptographyService : ICryptographyService
{
    public byte[] PasswordKeyByteArray { get; set; }
    public string CryptoKey { get; set; }

    public CryptographyService()
    {
        CryptoKey = "ASDLKFJALSDKFJAKDFJ";
        PasswordKeyByteArray = new byte[] {0x4b, 0x49, 0xa1, 0x6e, 0x11, 0x4d,
        0x58, 0x45, 0x76, 0x61, 0x62, 0x45, 0xa5};
    }
    //Encrypt a byte array into a byte array using a key and an IV
    public byte[] Encrypt(byte[] clearData, byte[] key, byte[] iv)
    {
        // Create a MemoryStream to accept the encrypted bytes
        var ms = new MemoryStream();
        var alg = Rijndael.Create();
        alg.Key = key;
        alg.IV = iv;
        var cs = new CryptoStream(ms,
        alg.CreateEncryptor(), CryptoStreamMode.Write);
        cs.Write(clearData, 0, clearData.Length);
        cs.Close();
        byte[] encryptedData = ms.ToArray();
        return encryptedData;
    }

    public string Encrypt(string clearText)
    {
        if (string.IsNullOrEmpty(clearText))
        {
            return clearText;
        }
        byte[] clearBytes = Encoding.Unicode.GetBytes(clearText);
        var pdb = new Rfc2898DeriveBytes(CryptoKey, PasswordKeyByteArray);
        byte[] encryptedData = Encrypt(clearBytes, pdb.GetBytes(32), pdb.GetBytes(16));
        return Convert.ToBase64String(encryptedData);

    }
    public byte[] Decrypt(byte[] cipherData,
        byte[] key, byte[] iv)
    {
        var ms = new MemoryStream();
        var alg = Rijndael.Create();
        alg.Key = key;
        alg.IV = iv;
        var cs = new CryptoStream(ms, alg.CreateDecryptor(), CryptoStreamMode.Write);
        cs.Write(cipherData, 0, cipherData.Length);
        cs.Close();
        byte[] decryptedData = ms.ToArray();

        return decryptedData;
    }
    public bool TryDecrypt(string cipherText, out string result)
    {
        if (string.IsNullOrEmpty(cipherText))
        {
            result = cipherText;
            return false;
        }
        try
        {
            byte[] cipherBytes = Convert.FromBase64String(cipherText);
            var pdb = new Rfc2898DeriveBytes(CryptoKey, PasswordKeyByteArray);
            byte[] decryptedData = Decrypt(cipherBytes, pdb.GetBytes(32), pdb.GetBytes(16));
            result = Encoding.Unicode.GetString(decryptedData);
            return true;
        }
        catch (Exception)
        {
            result = null;
            return false;
        }
    }
}

Summary

Now we store our sensitive information from our users submissions encrypted. I really like the new pluggable architecture of Episerver. It makes it possible to extend almost anything.

Happy coding everyone!

Jul 13, 2016

Comments

Please login to comment.
Latest blogs
Optimizely Configured Commerce and Spire CMS - Figuring out Handlers

I recently entered the world of Optimizely Configured Commerce and Spire CMS. Intriguing, interesting and challenging at the same time, especially...

Ritu Madan | Mar 12, 2025

Another console app for calling the Optimizely CMS REST API

Introducing a Spectre.Console.Cli app for exploring an Optimizely SaaS CMS instance and to source code control definitions.

Johan Kronberg | Mar 11, 2025 |

Extending UrlResolver to Generate Lowercase Links in Optimizely CMS 12

When working with Optimizely CMS 12, URL consistency is crucial for SEO and usability. By default, Optimizely does not enforce lowercase URLs, whic...

Santiago Morla | Mar 7, 2025 |

Optimizing Experiences with Optimizely: Custom Audience Criteria for Mobile Visitors

In today’s mobile-first world, delivering personalized experiences to visitors using mobile devices is crucial for maximizing engagement and...

Nenad Nicevski | Mar 5, 2025 |

Unable to view Optimizely Forms submissions when some values are too long

I discovered a form where the form submissions could not be viewed in the Optimizely UI, only downloaded. Learn how to fix the issue.

Tomas Hensrud Gulla | Mar 4, 2025 |

CMS 12 DXP Migrations - Time Zones

When it comes to migrating a project from CMS 11 and .NET Framework on the DXP to CMS 12 and .NET Core one thing you need to be aware of is the...

Scott Reed | Mar 4, 2025