簡體   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