1

I have the following class with service for AES encryption and decryption. Everything works fine until .Net 5. After migrating to .Net 6, the decryption method returns incomplete text.

Cryptography class:

using System;
using System.IO;
using System.Security.Cryptography;
using System.Text;

namespace framework.mstiCSharp.Services
{
    public class CriptografiaService
    {
        #region Settings

        private static int _iterations = 2;
        private static int _keySize = 256;

        private static string _hash = "SHA1";
        private static string _salt = "aselrias38490a32"; // Random
        private static string _vector = "8947az34awl34kjq"; // Random

        #endregion 

        public static string Encrypt(string value, string AesKey)
        {
            return Encrypt<AesManaged>(value, AesKey);
        }

        private static string Encrypt<RijndaelManaged>(string value, string password)
                where RijndaelManaged : SymmetricAlgorithm, new()
        {
            byte[] vectorBytes = Encoding.UTF8.GetBytes(_vector);
            byte[] saltBytes = Encoding.UTF8.GetBytes(_salt);
            byte[] valueBytes = Encoding.UTF8.GetBytes(value);

            byte[] encrypted;
            using (RijndaelManaged cipher = new RijndaelManaged())
            {
                PasswordDeriveBytes _passwordBytes =
                    new PasswordDeriveBytes(password, saltBytes, _hash, _iterations);
                byte[] keyBytes = _passwordBytes.GetBytes(_keySize / 8);

                cipher.Mode = CipherMode.CBC;

                using (ICryptoTransform encryptor = cipher.CreateEncryptor(keyBytes, vectorBytes))
                {
                    using (MemoryStream to = new MemoryStream())
                    {
                        using (CryptoStream writer = new CryptoStream(to, encryptor, CryptoStreamMode.Write))
                        {
                            writer.Write(valueBytes, 0, valueBytes.Length);
                            writer.FlushFinalBlock();
                            encrypted = to.ToArray();
                        }
                    }
                }
                cipher.Clear();
            }
            return Convert.ToBase64String(encrypted);
        }

        public static string Decrypt(string value, string AesKey)
        {
            return Decrypt<AesManaged>(value, AesKey);
        }

        private static string Decrypt<T>(string value, string password) where T : SymmetricAlgorithm, new()
        {
            byte[] vectorBytes = Encoding.UTF8.GetBytes(_vector);
            byte[] saltBytes = Encoding.UTF8.GetBytes(_salt);
            byte[] valueBytes = Convert.FromBase64String(value);

            byte[] decrypted;
            int decryptedByteCount = 0;

            using (T cipher = new T())
            {
                PasswordDeriveBytes _passwordBytes = new PasswordDeriveBytes(password, saltBytes, _hash, _iterations);
                byte[] keyBytes = _passwordBytes.GetBytes(_keySize / 8);

                cipher.Mode = CipherMode.CBC;

                try
                {
                    using (ICryptoTransform decryptor = cipher.CreateDecryptor(keyBytes, vectorBytes))
                    {
                        using (MemoryStream from = new MemoryStream(valueBytes))
                        {
                            using (CryptoStream reader = new CryptoStream(from, decryptor, CryptoStreamMode.Read))
                            {
                                decrypted = new byte[valueBytes.Length];
                                decryptedByteCount = reader.Read(decrypted, 0, decrypted.Length);
                            }
                        }
                    }
                }
                catch (Exception)
                {
                    return String.Empty;
                }

                cipher.Clear();
            }
            return Encoding.UTF8.GetString(decrypted, 0, decryptedByteCount);
        }
    }
}

Test class:

using framework.mstiCSharp.Services;
using Xunit;

namespace framework.mstiCSharpTest
{
    public class CriptografiaServiceTest
    {
        [Theory]
        [InlineData("abc123")]
        [InlineData("Silvair Leite Soares")]
        [InlineData("abcdefghij 1234567890")]
        public void encriptTest(string originalText)        
        {
            string key = "1sFnWG4HnV8TZY30iTOdtVWJG8abWvB1GlOgJuQZdcF2Luqm";

            string encriptText = CriptografiaService.Encrypt(originalText, key); 
            string decriptText = CriptografiaService.Decrypt(encriptText, key);

            Assert.Equal(originalText, decriptText);
        }
    }
}

I found this other question Problem Updating to .Net 6 - Encrypting String, and this issue AES Encryption broken on Dot Net 6, on this same subject. But I couldn't adapt the answers and suggestions to my situation.

Test cases:

Test 1
Original text Silvair Leite Soares
After encryption u2LcEdwpyTT4j+YJSYenJzFz0o+t0027DbvOn/i8bjU=
After decrypting Silvair Leite So
Test 2
Original text abc123
After encryption k3tyVen0ulvrsLJ/MuVevA==
After decrypting abc123
Test 3
Original text abcdefghij 1234567890
After encryption BUCUPbc1PhLOBvV9R2XP2NE7bWYQi5O4BjciiZd70pI=
After decrypting abcdefghij 12345

As can be seen, in some situations, with smaller text, it still works. But in larger texts, it fails every time.

Any help will be most welcome.

Silvair L. Soares
  • 1,018
  • 12
  • 28
  • 2
    Does this answer your question? [Problem Updating to .Net 6 - Encrypting String](https://stackoverflow.com/questions/69911084/problem-updating-to-net-6-encrypting-string). With regard to the UTF-8 decoding you performed at the end of your decryption, probably the last option in the accepted answer is the easiest (applying `StreamReader#ReadToEnd()`). – Topaco Jul 19 '22 at 14:41
  • Topaco, thanks for the suggestion. I even mentioned this other question in my question. But I couldn't adapt the suggestions of the answers of this other question to my case. Would you help me? – Silvair L. Soares Jul 19 '22 at 14:48
  • 1
    See here for a possible fix: https://dotnetfiddle.net/qoz0gE. – Topaco Jul 19 '22 at 15:06
  • I managed to solve. I will write an answer to my own question. Thank you Topaco. – Silvair L. Soares Jul 19 '22 at 15:06
  • Your suggestion solves my case. If you want to write an answer, I'll be happy to mark it as the solution. Thank you very much Topaco. – Silvair L. Soares Jul 19 '22 at 15:08

0 Answers0