0

I wrote a code for encrypting and decrypting sample text using the AES algorithm. When I click the first button, I want to encrypt the string which will display on the textbox1 and for second button click, decrypted value should display on textbox2.

This is the code for that:

public partial class _Default : Page
{
    public byte[] key = null; public byte[] iv = null; public byte[] bytesToEncrypt = null; public static byte[] encryptedBytes = null; public byte[] decryptedBytes = null;

    protected void Page_Load(object sender, EventArgs e)
    {
        RijndaelManaged aesAlg = new RijndaelManaged();
        aesAlg.GenerateKey();
        aesAlg.GenerateIV();
        key = aesAlg.Key;
        iv = aesAlg.IV;
    }

    protected void Button1_Click(object sender, EventArgs e)
    {
        // original bytes
        bytesToEncrypt = new byte[TextBox2.Text.ToString().Length * sizeof(char)];

        encryptedBytes = CryptoAes.Encrypt(bytesToEncrypt, key, iv);
        TextBox1.Text = Convert.ToBase64String(encryptedBytes);

        byte[] bytesToEncrypt1 = new byte[TextBox2.Text.Length];
        decryptedBytes = CryptoAes.Decrypt(encryptedBytes, key, iv);//working here.       
    }

    protected void Button2_Click(object sender, EventArgs e)
    {
        var s = Convert.FromBase64String(TextBox1.Text);                    
        decryptedBytes = CryptoAes.Decrypt(encryptedBytes, key, iv);
        TextBox2.Text = System.Text.Encoding.Unicode.GetString(decryptedBytes);//not working
    }
}

internal sealed class CryptoAes
{
    public static byte[] Encrypt(byte[] data, byte[] key, byte[] iv)
    {
        byte[] encryptedData = null;

        if (data == null)
            throw new ArgumentNullException("data");

        if (data == key)
            throw new ArgumentNullException("key");

        if (data == iv)
            throw new ArgumentNullException("iv");

        using (RijndaelManaged aesAlg = new RijndaelManaged())
        {
            aesAlg.Key = key;
            aesAlg.IV = iv;
            aesAlg.Padding = PaddingMode.Zeros;
            ICryptoTransform encryptor = aesAlg.CreateEncryptor(aesAlg.Key, aesAlg.IV);
            encryptedData = encryptor.TransformFinalBlock(data, 0, data.Length);
        }

        return encryptedData;
    }

    public static byte[] Decrypt(byte[] data, byte[] key, byte[] iv)
    {
        byte[] decryptedData = null;

        if (data == null)
            throw new ArgumentNullException("data");

        if (data == key)
            throw new ArgumentNullException("key");

        if (data == iv)
            throw new ArgumentNullException("iv");

        using (RijndaelManaged aesAlg = new RijndaelManaged())
        {
            aesAlg.Key = key;
            aesAlg.IV = iv;
            aesAlg.Padding = PaddingMode.Zeros;
            ICryptoTransform decryptor = aesAlg.CreateDecryptor(aesAlg.Key, aesAlg.IV);
            decryptedData = decryptor.TransformFinalBlock(data, 0, data.Length);

        }

        return decryptedData;
    }
}

For the first button click the decrypt is working fine. But when I click the second button the decrypted text shows some junk characters.

To figure out this I made the encryptedBytes as static and reuse it when I click the second button, but still the same output with junk values. I wonder how the same input gives the correct output when I click the first button.

Can anyone help me to sort out this?

6
  • So, you have input, have expected output you have code too.. then what will be the help you are expecting from us? is there any error? Commented Apr 22, 2016 at 9:59
  • Both the buttons are for decrypting? *"button click the decrypt is working fine" * Commented Apr 22, 2016 at 10:02
  • first button click,the decrypt is working fine. problem is with the second button click. First button is for encrypt and second is for decrypt. If i writing the logic for decrypting the code also in the first button, it works fine. Commented Apr 22, 2016 at 10:04
  • 3
    wont bytesToEncrypt just be an empty array? what are you trying to encrypt, the data in TextBox2.Text? Commented Apr 22, 2016 at 10:15
  • Its not empty array. It have values. I checked everything. But couldnt find out any difference. Please run the code and you can duplicate the issue. Commented Apr 22, 2016 at 11:21

2 Answers 2

1

I am having a working code of what you are trying have a look

            internal const string Inputkey = "560A18CD-6346-4CF0-A2E8-671F9B6B9EA9";

            public static string EncryptRijndael(string text, string salt)
            {
                if (string.IsNullOrEmpty(text))
                    throw new ArgumentNullException("text");

                var aesAlg = NewRijndaelManaged(salt);

                var encryptor = aesAlg.CreateEncryptor(aesAlg.Key, aesAlg.IV);
                var msEncrypt = new MemoryStream();
                using (var csEncrypt = new CryptoStream(msEncrypt, encryptor, CryptoStreamMode.Write))
                using (var swEncrypt = new StreamWriter(csEncrypt))
                {
                    swEncrypt.Write(text);
                }

                return Convert.ToBase64String(msEncrypt.ToArray());
            }


            public static bool IsBase64String(string base64String)
            {
                base64String = base64String.Trim();
                return (base64String.Length % 4 == 0) &&
                       Regex.IsMatch(base64String, @"^[a-zA-Z0-9\+/]*={0,3}$", RegexOptions.None);

            }


            public static string DecryptRijndael(string cipherText, string salt)
            {
                if (string.IsNullOrEmpty(cipherText))
                    throw new ArgumentNullException("cipherText");

                if (!IsBase64String(cipherText))
                    throw new Exception("The cipherText input parameter is not base64 encoded");

                string text;

                var aesAlg = NewRijndaelManaged(salt);
                var decryptor = aesAlg.CreateDecryptor(aesAlg.Key, aesAlg.IV);
                var cipher = Convert.FromBase64String(cipherText);

                using (var msDecrypt = new MemoryStream(cipher))
                {
                    using (var csDecrypt = new CryptoStream(msDecrypt, decryptor, CryptoStreamMode.Read))
                    {
                        using (var srDecrypt = new StreamReader(csDecrypt))
                        {
                            text = srDecrypt.ReadToEnd();
                        }
                    }
                }
                return text;
            }

            private static RijndaelManaged NewRijndaelManaged(string salt)
            {
                if (salt == null) throw new ArgumentNullException("salt");
                var saltBytes = Encoding.ASCII.GetBytes(salt);
                var key = new Rfc2898DeriveBytes(Inputkey, saltBytes);

                var aesAlg = new RijndaelManaged();
                aesAlg.Key = key.GetBytes(aesAlg.KeySize / 8);
                aesAlg.IV = key.GetBytes(aesAlg.BlockSize / 8);

                return aesAlg;
            }

            protected void Button1_Click(object sender, EventArgs e)
            {
                TextBox1.Text = EncryptRijndael(TextBox1.Text, Inputkey);
            }
            protected void Button2_Click(object sender, EventArgs e)
            {
                TextBox2.Text = DecryptRijndael(TextBox1.Text, Inputkey);
            }

Hope This help.

Sign up to request clarification or add additional context in comments.

1 Comment

how can I mention keysize and blocksize in this?
1

The bug is in your first line of code:

// original bytes
bytesToEncrypt = new byte[TextBox2.Text.ToString().Length * sizeof(char)];

If you inspect bytesToEncrypt, you will find it contains an array of all zeros:

Name             Value            Type
bytesToEncrypt   byte[]           System.Byte[]
├── [0]          0                byte
├── [1]          0                byte
├── [2]          0                byte
├── [3]          0                byte
├── [4]          0                byte
├── [5]          0                byte
├── [7]          0                byte
├── [8]          0                byte
├── [9]          0                byte
├── [10]         0                byte
├── [11]         0                byte
└── [12]         0                byte

You then encrypt all zeros.

And when you decrypt it, it returns you back all zeros.

You can fiddle with it here, on C# Fiddle.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.