JayGatsby
JayGatsby

Reputation: 1621

Encrypt a file with Rijndael algorithm

I found this code in a website

private void EncryptFile(string inputFile)
        {

                string password = @"myKey123"; // Your Key Here
                UnicodeEncoding UE = new UnicodeEncoding();
                byte[] key = UE.GetBytes(password);

                string cryptFile = inputFile + ".enc";
                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.Open);

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


                fsIn.Close();
                cs.Close();
                fsCrypt.Close();

        }

I have two problems with it. First one is the password part. I have a function which generates random strings:

public string CreatePassword(int length)
        {
            const string valid = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890*!=?&/";
            StringBuilder res = new StringBuilder();
            Random rnd = new Random();
            while (0 < length--){
                res.Append(valid[rnd.Next(valid.Length)]);
            }
            return res.ToString();
        }

When I edit the code like this:

string password = CreatePassword(8);

It works. But when I increase the password size (like 10) I get this error:

An unhandled exception of type 'System.Security.Cryptography.CryptographicException' occurred in mscorlib.dll

Is there way to increase password lenght? Or can we consider it safe with 8 lenght?

Other question:

my output file is inputFile + ".enc" When I delete ".enc" Part I got "this file using by another process" error. How can write encrypted one to original one?

Upvotes: 2

Views: 767

Answers (1)

mkysoft
mkysoft

Reputation: 5758

RijndaelManaged has rules. Below command used for preparing algorithm:

RMCrypto.CreateEncryptor(key, key)

First param is secret key and it must be 128, 192, or 256 bits. Second param is IV. In given example, key and IV used as same. Password text convert to byte with unicode so it is length 16 byte = 128 bit. So if you use different size then rule you get error.

You can check below article much better: Encrypting & Decrypting a String in C#

Upvotes: 2

Related Questions