2013-04-28 66 views
0

的事情是我一直在使用RSA使用此代碼,我想出了加密的文件:RSA加密大文件

 for (int a = 0; a <= iterations; a++) 
     { 
      byte[] plain; 
      int rsaLen = rsa.KeySize/8 - 11; 
      int bytesLen = plain.Length; 
      int block = bytesLen - rsaLen * a; 

      //The last block in the text may not be a full block 
      if (block > rsaLen) 
       plain = new byte[maxRsaLength]; 
      else 
       plainblock = new byte[block]; 

      Buffer.BlockCopy(plaintext, rsaLen * a, plain, 0, plain.Length); 

      //purfoming the encryption 
      ciphertext.Append(Convert.ToBase64String(rsa.Encrypt(plain, false))); 
     } 

的事情是,當我嘗試解密我有密文轉換我已經把基地64 64基地塊,但後來我從RSAServiceProvider的解密方法得到一個不好的長度exceptioon。我一直在關注這個網站上寫的例子: http://digitalsquid.co.uk/2009/01/rsa-in-cs/無濟於事。我沒有得到任何加密錯誤只是解密。我甚至不能確定我是否已經完成了加密權。貝婁是我的解密循環:

public string Decrypt(string ciphertext, string key = null) 
    { 
     //checking for ciphertext. Exception raise if null 
     if (String.IsNullOrEmpty(ciphertext)) throw new ArgumentNullException(ciphertext, "There is no ciphertext to decrypt."); 

     //String holding the decrypted value 
     string plaintext = String.Empty; 

     //chanck is the user has provided a key. If not the use the one automatically generated 
     string keyToUse = String.IsNullOrEmpty(key) ? privatekey : key; 

     //set the key 
     rsa.FromXmlString(keyToUse); 

     //Determine the blocksizes for the iterations 
     int blockSize = ((rsa.KeySize/8) % 3 != 0) ? (((rsa.KeySize/8)/3) * 4) + 4 : ((rsa.KeySize/8)/3) * 4; 

     int iterations = ciphertext.Length/blockSize; 
     byte[] allPlaintextAsBytes = new byte[0]; 


     try 
     { 
      for (int i = 0; i < iterations; i++) 
      { 
       //to decrypt this we have to take the cipher text from a base 64 string an array. 
       byte[] cipherTextAsBytes = Convert.FromBase64String(ciphertext.Substring(blockSize * i, blockSize)); 

       byte[] partialPlaintextAsBytes = rsa.Decrypt(cipherTextAsBytes, false); 
      } 
     }....(Catch Exceptions down here) 

我知道這不是最好把文件分割成RSA。通常情況下,您可以使用RSA將密鑰加密爲AES等流密碼,並使用AES對文件進行加密。這是我正在做的一個項目,所以我必須這樣做。

感謝您提前給予幫助。

+3

確保分配項目的人指出,這對其他可能不知道這一點的學生來說很愚蠢。嵌套對稱加密不僅僅是一個安全慣例:它對使用RSA進行直接加密是非常不安全的。我不想讓一代學生走出這個項目,認爲這種做法在任何方面都沒問題。 – 2013-04-28 17:35:32

+0

@MyseriousDan我會不同意一點。當然,這樣做很愚蠢。但是,「直接」RSA加密是安全的。 – 2013-04-29 07:47:38

+0

有點傻是的。用512或128加密是愚蠢的,但它可以幫助人們開始理解這些數字是如何工作的。他讓我這樣做的原因是我能夠做到這一點。通過這個項目,我已經瞭解到,分組密碼不能加密大於模數的塊。在我得到這個項目之前,我不知道這一點。我可以放心地說,我不是專家,但那些不應該僅僅摒棄這個問題,甚至不僅僅因爲它的不尋常的做事方式而回答它。問題是關於我寫的代碼不工作,不是概念 – 2013-04-29 13:03:01

回答

0

真實世界的RSA實現會影響可以加密的明文的最大長度。

特別是,PKCS#1填充(最常見的)只支持k-11個字節長的明文,其中k是密鑰長度。 OAEP填充只接受高達k-2 *散列長度的明文 - 長度爲2(OAEP允許你改變你使用的散列算法)。