Encryption using rijndael

I am new to programming. I wrote the code below to request a password to encrypt the file, but it just works when the password is 8, what can I do to accept any number of characters for the password?

string pass = textBox2.Text.ToString(); string password = @"" + pass + ""; UnicodeEncoding UE = new UnicodeEncoding(); byte[] key = UE.GetBytes(password); FileStream fsCrypt = new FileStream(@"c:\\users\\new", FileMode.Create); name = fsCrypt.Name; RijndaelManaged RMCrypto = new RijndaelManaged(); CryptoStream cs = new CryptoStream(fsCrypt, RMCrypto.CreateEncryptor(key, key), CryptoStreamMode.Write); FileStream fsIn = new FileStream(filename, FileMode.Open); int data; while ((data = fsIn.ReadByte()) != -1) cs.WriteByte((byte)data); 
+6
c #
source share
3 answers

Directly obtaining the key form, your password using Encoding.GetBytes() will work only if the result of GetBytes () is legitimate KeySize.

More importantly, it makes a very weak key, especially since you have chosen Unicode encoding. The byte pattern in your key for "foobar" is 66 00 6F 00 6F 00 62 00 61 00 72 00 . Do you see all 00 bytes?

The official way is to use the Rfc2898DeriveBytes class. Also, it is probably not recommended to use the key as an IV, I'm not quite sure about this.

Also see this SO question .

+1
source share

You need a function that will receive the actual key length for Rijndael from your password, and for now, your use of UnicodeEncoding.GetBytes will only give this for certain discrete password lengths, since you are detected.

You should use another function to get the key to your password - perhaps take the byte array you created and run a cryptographic hash function such as SHA1. SHA1 will provide you with a length of 128 bits, for example, your 8-character passwords, but regardless of the password length.

+2
source share

Check out PasswordDeriveBytes

http://msdn.microsoft.com/en-us/library/system.security.cryptography.passwordderivebytes(v=VS.100).aspx

You will need a fixed salt value, as well as the passed value, this will stop people developing passwords from the algorithm.

It is also used for TripleDES and should be easily modified for Rijndael:

 // Create a TripleDESCryptoServiceProvider object. TripleDESCryptoServiceProvider tdes = new TripleDESCryptoServiceProvider(); // Create a PasswordDeriveBytes object and then create // a TripleDES key from the password and salt. PasswordDeriveBytes pdb = new PasswordDeriveBytes(pwd, salt); // Create the key and set it to the Key property // of the TripleDESCryptoServiceProvider object. tdes.Key = pdb.CryptDeriveKey("TripleDES", "SHA1", 192, tdes.IV); 
0
source share

All Articles