I’m quite new in programming .I wrote the below code in order to prompt the user for a password to encrypting a file, But it just work when the length of password is 8, What can I do on order to accepting 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);
Directly deriving a Key form your password with
Encoding.GetBytes()will only work if the result of GetBytes() is a legal KeySize.More important, it makes a very weak Key, especially as you opted for the 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 the 00 bytes?The official way is to use the
Rfc2898DeriveBytesclass. Also it is probably not a good idea to use the Key as IV, I’m not entirely sure about this.Also see this SO question.