In Asp.NET you can use the MachineKey.Protect to encrypt data. We are thinking of using this to encrypt some data which will be stored in a hidden fields within a web page, these hidden fields are used when the web page is posted back.

I have read that when encrypting it is better to use a different Initialisation Vector each time as if the same one is used over and over again the encryption becomes easier to crack.

Surely by using MachineKey.Protect over and over again the encryption becomes easier to crack as the same IV is being used. The data I am protecting is not super sensitive so I don't need a gold standard solution, I am just checking that I am not about to do something that is very weak. If MachineKey.Protect is a medium strength solution that is fine.

Thanks for your help.

1 Answer 1


The MachineKey.Protect method automatically generates a random IV during encryption. You can see this in effect by protecting the same values multiple times:

for (int n = 0; n < 10; n++)
    byte[] data = MachineKey.Protect(Encoding.ASCII.GetBytes("This is a test."), "testing");
    var sb = new StringBuilder();
    for (int i = 0; i < data.Length; i++)
        sb.AppendFormat("{0:x2}", data[i]);



If you step into the decompiled sources for System.Web.dll and System.Security.dll, you'll find that the MachineKey.Protect call loads a provider from a factory which ultimately wraps the underlying DPAPI protection methods - specifically CryptProtectData, using the hash of the purposes list as the "optional entropy" field. The DPAPI automatically applies a salt and a MAC.

  • I would have thought that the machinekey would have needed the random iv to decrypt the string?
    – Jake
    Commented May 18, 2015 at 18:18
  • @Jake Yes. The IV is embedded within the output data.
    – Polynomial
    Commented May 18, 2015 at 19:00
  • 5
    Correction: MachineKey.Protect doesn't use DPAPI by default. It instead uses information derived from the value of <machineKey> stored in Web.config. (This also allows it to work in a server farm, whereas using DPAPI wouldn't allow for this.) The security of MachineKey.Protect depends on the quality of the entropy in <machineKey> and the steps taken to shield that value from unauthorized access, e.g., by employing encrypted config.
    – Levi
    Commented Jul 12, 2015 at 23:52
  • @Levi This may depend on which version of the .NET framework you load, and whether you're looking at the desktop or web platform. The info above was derived from reverse engineering the framework assemblies, so I guess we're looking at different versions.
    – Polynomial
    Commented Jul 13, 2015 at 8:55
  • 2
    @Polynomial The behavior hasn't changed since its introduction in .NET 4.5. I should know - I wrote the code. :)
    – Levi
    Commented Jul 13, 2015 at 22:11

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .