How to make AesEncrypterHandler encrypt the same way as Aes does

63 views Asked by At

I am trying to use AesCryptoServiceProvider to achieve the same encryption mechanism as Aes. Here is my AesCryptoServiceProvider version of it:

        public string version1(string plainText, string encryptionKey, string initializationVector)
        {
            AesCryptoServiceProvider provider = new AesCryptoServiceProvider
            {
                BlockSize = 128,
                Padding = PaddingMode.PKCS7,
                Key = Convert.FromBase64String(encryptionKey),
                IV = Encoding.UTF8.GetBytes(initializationVector)
            };

            byte[] buffer = Encoding.ASCII.GetBytes(plainText);
            byte[] encrypted = provider.CreateEncryptor().TransformFinalBlock(buffer, 0, buffer.Length);
            return Convert.ToBase64String(encrypted);
        }

And here is the Aes version of it:

        public string version2(string plainText, string encryptionKey, string initializationVector)
        {
            byte[] clearBytes = Encoding.UTF8.GetBytes(plainText);
            byte[] encryptedBytes;
            byte[] iv = Encoding.UTF8.GetBytes(initializationVector);

            using (Aes aes = Aes.Create())
            {
                aes.BlockSize = 128;
                aes.Padding = PaddingMode.PKCS7;
                aes.Key = Convert.FromBase64String(encryptionKey);
                aes.IV = iv;

                using (MemoryStream ms = new MemoryStream())
                using (CryptoStream cs = new CryptoStream(ms, aes.CreateEncryptor(), CryptoStreamMode.Write))
                {
                    cs.Write(clearBytes, 0, clearBytes.Length);
                    cs.Close();
                    encryptedBytes = ms.ToArray();
                }
            }

            byte[] ivEncryptedBytes = new byte[iv.Length + encryptedBytes.Length];
            Buffer.BlockCopy(iv, 0, ivEncryptedBytes, 0, iv.Length);
            Buffer.BlockCopy(encryptedBytes, 0, ivEncryptedBytes, iv.Length, encryptedBytes.Length);

            return Convert.ToBase64String(ivEncryptedBytes);
        }

When I encrypt the same string using version1 and version2 they came out to be different. Any idea on how these two methods are different and how I can make version1 produces the same encrypted string as version2? (p.s. I am rather new to encryption so sorry if the answer is obvious) Thanks!

1

There are 1 answers

0
cxc On

As @MichaelFehr pointed out, version2 only has the initialization vector and the encrypted bytes concatenated together before converting the bytes back to string. I have tested that if I concatenate the string the same way as version2 in version1, the result string will become the same.