如何在ubuntu中使用RSACryptoServiceProvider()解密c#中的加密数据?

时间:2012-05-29 10:51:16

标签: c# encryption mono cryptography rsa

我正在使用c#中的RSACryptoServiceProvider()类加密我的数据。我想解密ubuntu中用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 个答案:

答案 0 :(得分:1)

不要那样使用RSA。它并不意味着以这种方式使用,而且速度太慢。

方式是使用对称算法,例如AES,并加密您使用RSA的密钥。请参阅我的old blog entry了解C#代码。

答案 1 :(得分:0)

你需要相同的机制,但相反。先试试,稍后再问。