0

我正在使用RSACryptoServiceProvider()c# 中的类来加密我的数据。我想解密在 c# 中加密的 ubuntu 中的数据。您能否建议我需要遵循哪种机制才能解密。以下函数用于加密:

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);
    }
} 
4

2 回答 2

1

不要那样使用 RSA。它不适合那样使用,而且太慢了。

正确的方法是使用对称算法,例如 AES,并使用 RSA 加密您使用的密钥。请参阅我的旧博客条目,了解这样做的 C# 代码。

于 2012-05-30T21:41:50.330 回答
0

您需要相同的机制,但相反。先试后问。

于 2012-06-01T14:10:28.823 回答