.NET Development Examined

Welcome to TexasJetter

This site’s purpose is to share tips, tricks, and techniques I have learned in my day to day workings as a developer. Topics you may find here will cover mostly Microsoft technologies, such as ASP.NET, MVC, WCF, and WPF. Along the way you may find a little jQuery and JavaScript thrown in to keep things dynamic.

This site also serves as a repository of how items of interest have been done, or might be done when I have the future need. I know in my travels across the Internet I come across a wide range of interesting topics, some of which I may not have a use for at the time but want to keep in mind should I need them in the future. Occasionally a topic will inspire me enough to work through the technique, even though I am not currently using it. In that case it will show up here.

- Enjoy

Encrypt C# Object

Wednesday, December 30, 2015

One of the things I've been doing a lot of lately is taking a C# class and encrypting it into a string suitable for storage as a cookie. Typically the process has been to write a helper method to encrypt and another to decrypt for each class object. The process is fairly simple, build a string representation of the class then encrypt it. It looks something like this:

public static byte[] PrivateKey = new byte[] { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24 };
public static string EncryptCustomer(Customer customer)
	if (customer == null){ return string.Empty;	}
	var customerString = new StringBuilder();
	customerString.AppendFormat("|FirstName:{0}", customer.FirstName);
	customerString.AppendFormat("|LastName:{0}", customer.LastName);
	return SecurityHelper.EncryptString(customerString.ToString(), PrivateKey);

To get the encrypted string back to a class we first decrypted the string, then parsed the array. That typically looked like this:

Read More

Comments (0)