[C#] 關於RSA 加密長度問題

2013-02-18


關於RSA 加解密,其實很多文章都已經寫過了
大家可以參考
這邊提供我參考連結:

余小章 - [C#.NET] 字串及檔案,利用 RSA 演算法加解密
亂馬客 - [.NET]使用RSA憑證加/解密
程式勞工的汗水 -[C#]RSA 加密長度錯誤
MSDN 論壇 - http://social.msdn.microsoft.com/forums/en-US/netfxbcl/thread/d516f0e6-6e14-4d5f-9170-3a1eb7715077

為什麼還要在寫一篇文章,是因為我遇到,關於長度問題,也感謝論壇跟亂馬客的文章
讓我學習起來比較不痛,但是稍微整理一下變成自己需要的function 然後在這邊也筆記一下..
在上面我寫到那MSDN 上面他解法很漂亮,因為有Keysize的問題使用block的方法進行分段處理..

加密function :

public static string EncryptData(string data, string publicKey,int encryptionBufferSize=117,int decryptionBufferSize=128)
{
    var rsa = new RSACryptoServiceProvider();
    rsa.FromXmlString(publicKey);
    byte[] dataEncoded = Encoding.UTF8.GetBytes(data);
    using (var ms = new MemoryStream())
    {
        var buffer = new byte[encryptionBufferSize];
        int pos = 0;
        int copyLength = buffer.Length;
        while (true)
        {
            if (pos + copyLength > dataEncoded.Length)
            {
                copyLength = dataEncoded.Length - pos;
            }
            buffer = new byte[copyLength];
            Array.Copy(dataEncoded, pos, buffer, 0, copyLength);
            pos += copyLength;
            ms.Write(rsa.Encrypt(buffer, false), 0, decryptionBufferSize);
            Array.Clear(buffer, 0, copyLength);
            if (pos >= dataEncoded.Length)
            {
                break;
            }

        }

        var res = Convert.ToBase64String(ms.ToArray());
        return res;
    }
}

解密function :


public static string DecryptData(string encryptContent, string privateKey, int decryptionBufferSize = 128)
{
    try
    {
        var data = Convert.FromBase64String(encryptContent);
        var rsa = new RSACryptoServiceProvider();
        rsa.FromXmlString(privateKey);
        using (var ms = new MemoryStream(data.Length))
        {
            byte[] buffer = new byte[decryptionBufferSize];
            int pos = 0;
            int copyLength = buffer.Length;
            while (true)
            {
                Array.Copy(data, pos, buffer, 0, copyLength);
                pos += copyLength;
                byte[] resp = rsa.Decrypt(buffer, false);
                ms.Write(resp, 0, resp.Length);
                Array.Clear(resp, 0, resp.Length);
                Array.Clear(buffer, 0, copyLength);
                if (pos >= data.Length)
                {
                    break;
                }
            }
            return Encoding.UTF8.GetString(ms.ToArray());
        }
    }

    catch (CryptographicException ce)
    {
        throw ce;
    }
}


其中很多東西我就不贅述了,前輩們文章都寫得很棒,在這邊項社群前輩鞠躬..

有需要的這邊有提供簡單範例,可以下載來玩玩


當麻許的超技八 2014 | Donma Hsu Design.