Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Which of the AES classes in the System.Security.Cryptography namespace should I use?

The System.Security.Cryptography namespace has at least 3 different seemingly interchangeable ways to get an object that will perform AES encryption/decryption:

using (var aes = Aes.Create())

or

using (var aes = new AesCryptoServiceProvider())

or

using (var aes = new AesCng())

The first two were introduced in .NET framework version 3.5. The third is much newer; it was introduced in version 4.6.2. One might suspect therefore that it is better than the other 2, but the documentation does not say anywhere that it is recommended to use it in place of the other ones.

The first two each have a code sample. The two samples appear essentially identical.

Which one should I use, and why?

like image 701
Hammerite Avatar asked Jan 08 '18 16:01

Hammerite


1 Answers

Aes is an abstract class. I assume that Aes.Create returns a system default. This is probably what you want to use. Let the system decide which ones are available and which ones is best to use.

The others are implementation classes.

  • AesCryptoServiceProvider uses MS CAPI, the older crypto API;
  • AesCng uses the crypto new generation API introduced in Windows Vista;
  • AesManaged implements AES in .NET (not mentioned in your post).

You can also use Aes.Create(string) to choose one of the implementations. If possible I would try and avoid using the implementation classes directly.

Only use the implementation classes if you know that using a specific class is explicitly required or, indeed, if the abstract Aes class is not available.


Note that exposing the crypto implementations in the type system by Microsoft has significant drawbacks; choosing a specific provider may be harder, key based implementation selection may be harder (encryption in hardware) and finally users may be tricked into writing incompatible or inefficient code.

The CipherSpi implementation classes in Java e.g. are hidden from view; these are called from the generic Cipher class.

like image 178
Maarten Bodewes Avatar answered Oct 23 '22 22:10

Maarten Bodewes