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?