RijndaelManaged difference in .NET Framework and .NET Core

493 Views Asked by At

I am using exactly same class for Encrypting/Decrypting the string in two project , one project is targeting .NET Framework 4.8 and second .NET 5 . I have faced pretty strange thing with RijndaelManaged Algorithm , on .NET Framework application it works perfectly fine but on .NET 5 it throws "Specified key is not a valid size for this algorithm" error.

First question I have is why error doesn't occurs in .NET Framework app (I know that versions of System.Security.Cryptography dll is different for projects) , the key I am using is 12 bytes . As I have researched RijndaelManaged key accepts only 16/24/32 byte in .NET Framework and only 16 byte in .NET Core , as written in Remarks here - https://learn.microsoft.com/en-us/dotnet/api/system.security.cryptography.rijndaelmanaged?view=net-5.0

this.key = Convert.FromBase64String(Convert.ToBase64String(Encoding.UTF8.GetBytes("qwertyuiopas")))

This is how I get byte array for key , and it's 12 byte long.

How can I make this encryption work in .NET Core/5 application ?

Would appreciate any ideas , Thanks in advance !

Note : I can't change anything in .NET Framework app , I am working on .Net 5 project and I need to get valid encrypted string which then will get decrypted in .NET Framework application .

1

There are 1 best solutions below

0
ste-fu On

If you want your key to be of a fixed byte size, create it as that, and then convert it to base 64 for ease of storage.

You can do it in a separate console app if you want. Something like:

var rng = new RNGCryptoServiceProvider();

var key = new byte[16];
rng.GetNonZeroBytes(key);

var base64Key = Convert.ToBase64String(key);

return base64Key;