2
一個文件,我發現這個代碼在網站加密與Rijndael算法
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();
}
我有兩個問題吧。第一個是password
部分。我有一個生成隨機字符串的函數:
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();
}
當我編輯這樣的代碼:
string password = CreatePassword(8);
它的工作原理。但是當我增加密碼大小(如10),我得到這個錯誤:
An unhandled exception of type 'System.Security.Cryptography.CryptographicException' occurred in mscorlib.dll
有沒有辦法增加密碼長度?或者我們可以認爲它是安全的8長度?
其他問題:
我的輸出文件inputFile + ".enc"
當我刪除".enc"
第一部分我「這個文件是使用由另一個進程」錯誤。如何將加密的文件寫入原始文件?
您是否在調試模式下運行它,並提取有關該問題的更詳細的異常? – Jens
您不應該直接使用密碼作爲密鑰,您應該使用['Rfc2898DeriveBytes'](https://msdn.microsoft.com/en-us/library/system)的基於密碼的密鑰派生函數「PBKDF」。 security.cryptography.rfc2898derivebytes(v = vs.110).aspx)類,其中包含PBKDF2。將密碼字符串傳入,然後使用它獲取所需的字節數。 –