user1849946
user1849946

Reputation: 19

Rijndael Cipher error in c# windows form

I am currently interested in furthering my programming skills in encryption and decryption and found a number of examples for the Rijndael cipher.

I start to program my own in c#, i click my encrypt button which opens a dialog window to allow me to choose a file....all works ok so far

I choose a file, and step through my code, i get t he root path for my file, generate a key and then i start to convert my plain text into cipher text...here's where i hit the problem.

 try
        {
            OpenFileDialog dialog = new OpenFileDialog();
            dialog.Filter = "All Files (*.*)|";
            dialog.InitialDirectory = @"Desktop";
            dialog.Title = "Please select a file to encrypt.";

            dialog.ShowDialog();

            inputFile = dialog.FileName;
            outputFile = inputFile;

            string password = @"secrets"; // key to encrypt files
            UnicodeEncoding UE = new UnicodeEncoding();
            byte[] key = UE.GetBytes(password);

            string cryptFile = outputFile;
            FileStream fsCrypt = new FileStream(cryptFile, FileMode.Create);

            RijndaelManaged RMCrypto = new RijndaelManaged();

            CryptoStream cs = new CryptoStream(fsCrypt,
                RMCrypto.CreateEncryptor(key, key),
                CryptoStreamMode.Write);

            FileStream fsIn = new FileStream(inputFile, FileMode.Append);

            int data;
            while ((data = fsIn.ReadByte()) != -1)
                cs.WriteByte((byte)data);


            fsIn.Close();
            cs.Close();
            fsCrypt.Close();
        }
        catch(Exception ex)
        {
            MessageBox.Show(ex.ToString());
        }
    }

the problem hits when i reach this piece of code

 CryptoStream cs = new CryptoStream(fsCrypt,
                RMCrypto.CreateEncryptor(key, key),
                CryptoStreamMode.Write);

the error i get is system.windows.forms.mouseeventargs can anybody help me out there?

EDIT!!! this is the actual error message my mistake.. Specified initialization vector (IV) does not match the block size for this algorithm.

Upvotes: 0

Views: 756

Answers (3)

Justin Bannister
Justin Bannister

Reputation: 618

Here is some code which opens up the selected file and encrypts in in the same directory with a random file name.

private void button1_Click(object sender, EventArgs e)
    {
        try
        {
            var dialog = new OpenFileDialog
                {
                    Filter = "All Files (*.*)|",
                    InitialDirectory = @"Desktop",
                    Title = "Please select a file to encrypt."
                };

            dialog.ShowDialog();

            string inputFile = dialog.FileName;

            // NOTE: The password should not be hardcoded in here
            const string password = @"secrets";

            var fileInfo = new FileInfo(inputFile);

            if(fileInfo.Directory != null)
            {
                string cryptFile = Path.Combine(fileInfo.Directory.ToString(),
                                                Path.GetRandomFileName());

                using (var rijndael = InitSymmetric(Rijndael.Create(), password, 256))
                {

                    using(var fsCrypt = new FileStream(cryptFile, FileMode.Create))
                    {
                        using (var cs = new CryptoStream(fsCrypt,
                                                         rijndael.CreateEncryptor(),
                                                         CryptoStreamMode.Write))
                        {
                            using (var fsIn = new FileStream(inputFile, FileMode.Open))
                            {
                                int data;

                                while ((data = fsIn.ReadByte()) != -1)
                                {
                                    cs.WriteByte((byte)data);
                                }
                            }
                        }
                    }
                }
            }

        }
        catch(Exception ex)
        {
            MessageBox.Show(ex.ToString());
        }
    }

    public static SymmetricAlgorithm InitSymmetric(SymmetricAlgorithm algorithm, string password, int keyBitLength)
    {
        // NOTE: Salt is for example purposes, would not normally have this in here.
        var salt = new byte[] { 1, 3, 66, 234, 73, 48, 134, 69, 250, 6 };
        const int iterations = 10000;

        var rfc2898DeriveBytes = new Rfc2898DeriveBytes(password, salt, iterations);

        if (!algorithm.ValidKeySize(keyBitLength))
            throw new InvalidOperationException("Invalid size key");
        algorithm.Key = rfc2898DeriveBytes.GetBytes(keyBitLength / 8);
        algorithm.IV = rfc2898DeriveBytes.GetBytes(algorithm.BlockSize / 8);
        return algorithm;
    }

Upvotes: 1

CodesInChaos
CodesInChaos

Reputation: 108790

You're putting your password directly into both key and IV. That's the wrong approach.

  1. The IV should be random and distinct for each encryption. Use the autogenerated IV and store it alongside the ciphertext.
  2. Use a real key, not a password. Alternatively send the password and a salt through PBKDF2, ask for 16 output bytes and use them as the key.

Upvotes: 0

igrimpe
igrimpe

Reputation: 1785

he error i get is system.windows.forms.mouseeventargs can anybody help me out there?

Look at the catch statement. You dont specify a variable to hold the exception, but inside you use e. Since you are in an eventhandler, e is already declared as parameter of the method.

Your catch should look like:

    catch (Exception ex)
    {
        // now ex holds your exception
    }

Specified initialization vector (IV) does not match the block size for this algorithm.

Use GenerateIV to create a valid IV. If you want to specify your own IV, make sure it fits the blocksize of the algorithm. In this case: 16 BYTE

Upvotes: 1

Related Questions