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;