2015-08-15 94 views
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"第一部分我「這個文件是使用由另一個進程」錯誤。如何將加密的文件寫入原始文件?

+0

您是否在調試模式下運行它,並提取有關該問題的更詳細的異常? – Jens

+0

您不應該直接使用密碼作爲密鑰,您應該使用['Rfc2898DeriveBytes'](https://msdn.microsoft.com/en-us/library/system)的基於密碼的密鑰派生函數「PBKDF」。 security.cryptography.rfc2898derivebytes(v = vs.110).aspx)類,其中包含PBKDF2。將密碼字符串傳入,然後使用它獲取所需的字節數。 –

回答

1

RijndaelManaged有規則。下面的命令用於準備算法:

RMCrypto.CreateEncryptor(key, key) 

第一個參數是密鑰,它必須是128,192或256位。第二個參數是IV。在給定的例子中,鍵和IV用作相同的。密碼文本使用unicode轉換爲字節,因此它的長度爲16字節= 128位。所以如果你使用不同的尺寸,那麼你會得到錯誤。

您可以查看下面的文章好得多: Encrypting & Decrypting a String in C#