繁体   English   中英

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

[英]How to decrypt an encrypted data in c# by using RSACryptoServiceProvider() in ubuntu?

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

不要那样使用RSA。 这并不是要那样使用,而且它太慢了。

正确的方法是使用对称算法(例如AES)并加密与RSA一起使用的密钥。 看到我的旧博客条目中的C#代码就是这样做的。

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM