Encryption Using MachineKey in .NET Framework

In .NET Framework 4.6, 4.5, 4 you can now encrypt your text using MachineKey in your web.config file. This encryption depend on System.Web.dll so you need to add reference of it before. NOTES:

  • If you have multiple web front end server, then the machine key should be same on all WFEs.
  • You may need to use Base64 encoding to convert encrypted or decrypted bytes to text so you can send it over HTTP,email or any textual transfer system.

Encrypt Method

 private static string Encrypt(string plainText)
 {
     byte[] plainTextBytes = Encoding.UTF8.GetBytes(plainText);

     byte[] encryptedBytes = MachineKey.Protect(plainTextBytes);

     string encryptedText = Convert.ToBase64String(encryptedBytes);

     return encryptedText;
 }

Decrypt Method

 private static string Decrypt(string encryptedText)
 {
     byte[] encryptedBytes = Convert.FromBase64String(encryptedText);

     byte[] plainTextBytes = MachineKey.Unprotect(encryptedBytes);

     string plainText = Encoding.UTF8.GetString(plainTextBytes);

     return plainText;
 }

Using New Code Nuggets in ASP.NET4

We will talk about new feature in ASP.NET 4.

Suppose you have the following code-behind property and you need to use it in ASPX page.

 

 

In ASPX page you can render the property MyContent like below:

 

 

And this will render the below output:

This is an XSS (cross-site script injection) and the developer should be aware of this, so he should do an HTMLEncode

 

Because of many developer may forget to do this, ASP.NET introduced the below code nugget

Now, the result will be;

Summery