From 5458c9a310a9aa189307565886f5cf97a8d271dd Mon Sep 17 00:00:00 2001 From: Shannon Deminick Date: Tue, 15 Jan 2013 01:35:10 +0300 Subject: [PATCH] Adds Encryption/Decryption string extension methods that work in medium trust, with unit tests. --- src/Umbraco.Core/StringExtensions.cs | 23 ++++++++++++++++++++++ src/Umbraco.Tests/StringExtensionsTests.cs | 10 ++++++++++ 2 files changed, 33 insertions(+) diff --git a/src/Umbraco.Core/StringExtensions.cs b/src/Umbraco.Core/StringExtensions.cs index 30634e75d1..3250a21d24 100644 --- a/src/Umbraco.Core/StringExtensions.cs +++ b/src/Umbraco.Core/StringExtensions.cs @@ -9,6 +9,7 @@ using System.Security.Cryptography; using System.Text; using System.Text.RegularExpressions; using System.Web; +using System.Web.Security; namespace Umbraco.Core { @@ -18,6 +19,28 @@ namespace Umbraco.Core /// public static class StringExtensions { + /// + /// Encrypt the string using the MachineKey in medium trust + /// + /// + /// + public static string EncryptWithMachineKey(this string toEncrypt) + { + var output = FormsAuthentication.Encrypt(new FormsAuthenticationTicket(0, "temp", DateTime.Now, DateTime.MaxValue, false, toEncrypt)); + return output; + } + + /// + /// Decrypt the encrypted string using the Machine key in medium trust + /// + /// + /// + public static string DecryptWithMachineKey(this string encrypted) + { + var output = FormsAuthentication.Decrypt(encrypted); + return output.UserData; + } + //this is from SqlMetal and just makes it a bit of fun to allow pluralisation public static string MakePluralName(this string name) { diff --git a/src/Umbraco.Tests/StringExtensionsTests.cs b/src/Umbraco.Tests/StringExtensionsTests.cs index 49f8f830d7..c00b3cebac 100644 --- a/src/Umbraco.Tests/StringExtensionsTests.cs +++ b/src/Umbraco.Tests/StringExtensionsTests.cs @@ -10,6 +10,16 @@ namespace Umbraco.Tests [TestFixture] public class StringExtensionsTests { + + [TestCase("This is a string to encrypt")] + public void Encrypt_And_Decrypt(string input) + { + var encrypted = input.EncryptWithMachineKey(); + var decrypted = encrypted.DecryptWithMachineKey(); + Assert.AreNotEqual(input, encrypted); + Assert.AreEqual(input, decrypted); + } + [TestCase("Hello this is my string", " string", "Hello this is my")] [TestCase("Hello this is my string strung", " string", "Hello this is my string strung")] [TestCase("Hello this is my string string", " string", "Hello this is my")]