0

I'm trying to encrypt and decrypt data from and to Laravel using C#

I've tried using this code. I've modified it to work correctly after Laravel's updates. however, when I try to decrypt the C# string in Laravel I recieve "The MAC is invalid." Exception.

I have no idea about what's the problem with the computation of the MAC on C# side.

Any ideas on how to solve this issue?

C# Code:

using System;
using System.Text;
using System.Security.Cryptography;
using System.Web.Script.Serialization;
using System.Collections.Generic;

namespace Aes256CbcEncrypterApp
{
    class MainClass
    {
        public static void Main(string[] args)
        {
            Console.WriteLine("Hello, world!");

            // The sample encryption key.
            byte[] Key = Convert.FromBase64String("My44CharKeyBase64");

            // The sample text to encrypt and decrypt.
            string Text = "Here is some text to encrypt!";

            // Encrypt and decrypt the sample text via the Aes256CbcEncrypter class.
            string Encrypted = Aes256CbcEncrypter.Encrypt(Text, Key);
            string Decrypted = Aes256CbcEncrypter.Decrypt(Encrypted, Key);

            // Show the encrypted and decrypted data and the key used.
            Console.WriteLine("Original: {0}", Text);
            Console.WriteLine("Key: {0}", Convert.ToBase64String(Key));
            Console.WriteLine("Encrypted: {0}", Encrypted);
            Console.WriteLine("Decrypted: {0}", Decrypted);

            Console.ReadKey();
        }
    }

    /**
     * A class to encrypt and decrypt strings using the cipher AES-256-CBC.
     */
    class Aes256CbcEncrypter
    {
        private static readonly Encoding encoding = Encoding.UTF8;

        public static string Encrypt(string plainText, byte[] key)
        {
            try
            {
                RijndaelManaged aes = new RijndaelManaged();
                aes.KeySize = 256;
                aes.BlockSize = 128;
                aes.Padding = PaddingMode.PKCS7;
                aes.Mode = CipherMode.CBC;

                aes.Key = key;
                aes.GenerateIV();

                ICryptoTransform AESEncrypt = aes.CreateEncryptor(aes.Key, aes.IV);
                byte[] buffer = encoding.GetBytes(plainText);

                string encryptedText = Convert.ToBase64String(AESEncrypt.TransformFinalBlock(buffer, 0, buffer.Length));

                String mac = "";

                mac = BitConverter.ToString(HmacSHA256(Convert.ToBase64String(aes.IV) + encryptedText, key)).Replace("-", "").ToLower();

                var keyValues = new Dictionary<string, object>
                {
                    { "iv", Convert.ToBase64String(aes.IV) },
                    { "value", encryptedText },
                    { "mac", mac },
                };

                JavaScriptSerializer serializer = new JavaScriptSerializer();

                return Convert.ToBase64String(encoding.GetBytes(serializer.Serialize(keyValues)));
            }
            catch (Exception e)
            {
                throw new Exception("Error encrypting: " + e.Message);
            }
        }

        public static string Decrypt(string plainText, byte[] key)
        {
            try
            {
                RijndaelManaged aes = new RijndaelManaged();
                aes.KeySize = 256;
                aes.BlockSize = 128;
                aes.Padding = PaddingMode.PKCS7;
                aes.Mode = CipherMode.CBC;
                aes.Key = key;

                // Base 64 decode
                byte[] base64Decoded = Convert.FromBase64String(plainText);
                string base64DecodedStr = encoding.GetString(base64Decoded);

                // JSON Decode base64Str
                JavaScriptSerializer serializer = new JavaScriptSerializer();
                var payload = serializer.Deserialize<Dictionary<string, string>>(base64DecodedStr);

                aes.IV = Convert.FromBase64String(payload["iv"]);

                ICryptoTransform AESDecrypt = aes.CreateDecryptor(aes.Key, aes.IV);
                byte[] buffer = Convert.FromBase64String(payload["value"]);

                return encoding.GetString(AESDecrypt.TransformFinalBlock(buffer, 0, buffer.Length));
            }
            catch (Exception e)
            {
                throw new Exception("Error decrypting: " + e.Message);
            }
        }

        static byte[] HmacSHA256(String data, byte[] key)
        {
            using (HMACSHA256 hmac = new HMACSHA256(key))
            {
                return hmac.ComputeHash(encoding.GetBytes(data));
            }
        }
    }
}
Majx
  • 131
  • 14
  • Did you copy the code in your link exactly? Because it's getting the bytes for the key by calling `encoding.GetBytes`. In this case, `encoding` is `System.Text.Encoding.UTF8`. That seems really weird to me. Normally, I'd expect you to use `Convert.FromBase64String` to get the key in a case like this. Especially since the string being passed in is Base64 encoded... – Joshua Robinson Jan 16 '20 at 22:13
  • Yes, I modified it to work correctly using what you mentioned. But even after that I still get the MAC Invalid message. – Majx Jan 16 '20 at 22:15
  • @JoshuaRobinson I've edited the question after code modification. – Majx Jan 16 '20 at 23:11

1 Answers1

0

After digging, debugging, looking for any updates Laravel made and compared it to the C# code above, there was not any major deference, however the problem was at Laravel side and solved by entering these commands.

php artisan config:clear
php artisan cache:clear
php artisan view:clear
php artisan route:clear
composer dump-autoload

Remember to disable payload serialization while encrypting and decrypting to get the original payload and not a serialized one since serialization is enabled by default.

echo encrypt("test", false);
echo decrypt("base64EncryptedString", false)

In case more exceptions thrown from encrypt() or decrypt() try to open the browser in incognito mode or delete browser cache.

Majx
  • 131
  • 14