2012-05-29 48 views
0

我正在使用c#中的RSACryptoServiceProvider()類來加密我的數據。我想解密在Ubuntu中的數據,這是用c#加密的。你能告訴我爲了解密需要遵循哪種機制。下面的函數是加密:如何在ubuntu中使用RSACryptoServiceProvider()解密c#中的加密數據?

public static void Encrypt(String PublicKey, String plainText, out String cipherText) 
{ 
    try 
    {    
     int dwKeySize = 1024; 
     // TODO: Add Proper Exception Handlers 
     RSACryptoServiceProvider rsaCryptoServiceProvider = new RSACryptoServiceProvider(dwKeySize); 
     rsaCryptoServiceProvider.FromXmlString(PublicKey); 
     int keySize = dwKeySize/8; 
     byte[] bytes = Encoding.UTF32.GetBytes(plainText); 
     // The hash function in use by the .NET RSACryptoServiceProvider here is SHA1 
     // int maxLength = (keySize) - 2 - (2 * SHA1.Create().ComputeHash(rawBytes).Length); 
     int maxLength = keySize - 42; 
     int dataLength = bytes.Length; 
     int iterations = dataLength/maxLength; 
     StringBuilder stringBuilder = new StringBuilder(); 
     for (int i = 0; i <= iterations; i++) 
     { 
      byte[] tempBytes = new byte[(dataLength - maxLength * i > maxLength) ? maxLength : dataLength - maxLength * i]; 
      Buffer.BlockCopy(bytes, maxLength * i, tempBytes, 0, tempBytes.Length); 
      byte[] encryptedBytes = rsaCryptoServiceProvider.Encrypt(tempBytes, true); 
      // Be aware the RSACryptoServiceProvider reverses the order 
      // of encrypted bytes after encryption and before decryption. 
      // If you do not require compatibility with Microsoft Cryptographic API 
      // (CAPI) and/or other vendors. 
      // Comment out the next line and the corresponding one in the 
      // DecryptString function. 
      Array.Reverse(encryptedBytes); 
      // Why convert to base 64? 
      // Because it is the largest power-of-two base printable using only ASCII characters 
      stringBuilder.Append(Convert.ToBase64String(encryptedBytes)); 
     } 
     cipherText = stringBuilder.ToString(); 
    } 
    catch (Exception e) 
    { 
     cipherText = "ERROR_STRING"; 
     Console.WriteLine("Exception in RSA Encrypt: " + e.Message); 
     //throw new Exception("Exception occured while RSA Encryption" + e.Message); 
    } 
} 
+2

想過在你的Ubuntu安裝中使用Mono並在C#中創建等效的Decrypt方法? – Cheesebaron

+1

這裏的實際問題是什麼? –

+1

你有使用RSA加密多個塊的原因嗎?它速度很慢,有一些甜蜜的攻擊...... – emboss

回答

1

不要使用RSA這樣的。這並不意味着要這樣使用,而且速度太慢。

right方法是使用對稱算法,例如, AES,並對您使用RSA的密鑰進行加密。請參閱我的old blog entry以獲取C#代碼。

0

您需要相同的機制,但相反。先試一下,稍後再問。

相關問題