Reputation: 1929
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);
Upvotes: 6
Views: 1711
Reputation: 273169
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 Rfc2898DeriveBytes
class. 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.
Upvotes: 1
Reputation: 7526
Check out PasswordDeriveBytes
You'll need a fixed salt value as well as the passed, this stops people working out the passwords from the algorithm.
It's used like this for TripleDES and should be easy to modify 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);
Upvotes: 0
Reputation: 72840
You need a function that is going to get a valid key length for Rijndael from your password, and at the moment, your use of UnicodeEncoding.GetBytes
is only going to give this for certain discrete lengths of password, as you've discovered.
You should use another function to get a key from your password - perhaps take the byte array you have generated, and run a cryptographic hash function like SHA1 on it. SHA1 will give you a 128 bit length, like your 8 character passwords currently do, but regardless of the length of the password.
Upvotes: 2