Harish
Harish

Reputation: 574

"Specified cipher mode is not valid for this algorithm" in .NET CORE but working in .NET Standard

I am trying to decrypt aes encrypted file. I was able to successfully decrypt the file in .NET Standard. But when I used the same code in .NET Core, I am getting following exception.

System.Security.Cryptography.CryptographicException: 'Specified cipher mode is not valid for this algorithm.'

This is the code I'm using to decrypt.

public void FileDecrypt(string inputFile, string outputFile, string password)
    {
        byte[] passwordBytes = System.Text.Encoding.UTF8.GetBytes(password);
        byte[] salt = new byte[32];

        FileStream fsCrypt = new FileStream(inputFile, FileMode.Open);
        fsCrypt.Read(salt, 0, salt.Length);

        RijndaelManaged AES = new RijndaelManaged();
        AES.KeySize = 256;
        AES.BlockSize = 128;
        var key = new Rfc2898DeriveBytes(passwordBytes, salt, 50000);
        AES.Key = key.GetBytes(AES.KeySize / 8);
        AES.IV = key.GetBytes(AES.BlockSize / 8);
        AES.Padding = PaddingMode.PKCS7;
        AES.Mode = CipherMode.CFB;

        using (CryptoStream cs = new CryptoStream(fsCrypt, AES.CreateDecryptor(), CryptoStreamMode.Read))
        {
            using (FileStream fsOut = new FileStream(outputFile, FileMode.Create))
            {
                int read;
                byte[] buffer = new byte[1048576];

                while ((read = cs.Read(buffer, 0, buffer.Length)) > 0)
                {
                    fsOut.Write(buffer, 0, read);
                }
            }
        }
    }

If I remove Cipher Mode in .NET Core and decrypt, I'm getting Padding Invalid Exception.

System.Security.Cryptography.CryptographicException: 'Padding is invalid and cannot be removed.'

I changed different Padding Modes and tried, but the output file is invalid (not decrpted correctly).

Why am I getting Cipher Mode Invalid exception in .Net Core and not in .Net Standard ? What change should I make in .NET Core to decrypt correctly ?

I am using

.NET Core SDK (reflecting any global.json):
Version:   2.1.503

Upvotes: 4

Views: 3267

Answers (2)

Gonnagle
Gonnagle

Reputation: 132

CFB support was (re)introduced in .NET 5.0 via dotnet/runtime PR #38211.

Before .NET 5.0 the modes were indeed limited to CBC = 1, ECB = 2 and CTS = 5. Now CFB = 4 is also supported: https://github.com/dotnet/runtime/blob/main/src/libraries/System.Security.Cryptography.Primitives/src/System/Security/Cryptography/CipherMode.cs

Upvotes: 2

Vijay Yadav
Vijay Yadav

Reputation: 21

Currently only three modes are supported by .NET Core, (CBC = 1, CTS = 5, ECB = 2).

https://github.com/dotnet/corefx/blob/master/src/System.Security.Cryptography.Primitives/src/System/Security/Cryptography/CipherMode.cs

Upvotes: 2

Related Questions