Skip to content

Difference in symmetric encryption/decryption between .Net Core 5 and .Net Core 6 #63274

@brinkp

Description

@brinkp

The next program works fine in .Net Core 5 but fails in .Net Core 6. What am I missing?

using System.Diagnostics;
using System.Security.Cryptography;
using System.Text;

namespace TestCryptography
{
    public class Program
    {
        public static readonly byte[] Keys = {   9, 167,  34, 235, 227, 248, 149, 110,  39, 200, 191,  81, 174, 144, 100, 113, 137, 106,  73,  18, 160,  36, 122, 209, 234, 122,  97, 247, 243,  62,  73, 124 };
        public static readonly byte[] IV   = {  62,   7,  43, 180,  19,  18,  22, 122, 155, 207,  63, 188,  47,  42, 188,  19 };

        private static byte[] Encrypt(byte[] input, byte[] keys, byte[] iv)
        {
            using Aes aes = Aes.Create();

            ICryptoTransform encryptor = aes.CreateEncryptor(keys, iv);

            using MemoryStream memoryStream = new();
            using CryptoStream cryptoStream = new(memoryStream, encryptor, CryptoStreamMode.Write);

            cryptoStream.Write(input, 0, input.Length);
            cryptoStream.FlushFinalBlock();

            return memoryStream.ToArray();
        }

        private static byte[] Decrypt(byte[] encrypted, byte[] keys, byte[] iv)
        {
            using Aes aes = Aes.Create();

            ICryptoTransform decryptor = aes.CreateDecryptor(keys, iv);

            using MemoryStream memoryStream = new(encrypted);
            using CryptoStream cryptoStream = new(memoryStream, decryptor, CryptoStreamMode.Read);

            int numberOfBytes = encrypted.Length;

            byte[]  plainTextBytes = new byte[numberOfBytes];
            int decryptedByteCount = cryptoStream.Read(plainTextBytes, 0, numberOfBytes);

            return plainTextBytes.Take(decryptedByteCount).ToArray();
        }

        private static void Main()
        {
            string input      = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZabcdefg";

            byte[] inputAscii = Encoding.ASCII.GetBytes(input);

            byte[] encrypted  = Encrypt(inputAscii, Keys, IV);
            byte[] decrypted  = Decrypt(encrypted , Keys, IV);

            Debug.Assert(input.Length == decrypted.Length);
        }
    }
}

Metadata

Metadata

Assignees

No one assigned

    Labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions