RSA 是一種非對稱加密算法。因爲算法特性,加密和解密過程用不一樣密鑰,即公鑰和私鑰,而被普遍應用於數字證書的安全管理。 在具體應用中,公鑰用加密而私鑰用於解密,或 私鑰用於數字簽名而公鑰用於簽名驗證。因爲非對稱加密算法比價複雜,耗時較長,因此通常在網絡環境中RAS 被應用於 簽名認證,或小數據傳輸,如 AES 對稱密鑰傳輸。算法
在.Net 框架中,默認提供的輔助類只能對密鑰長度大小相同的數據進行加密解密。 此文提供C# RSA 算法示例一座優化,能夠不限數據大小。此實例 僅供交流學習。安全
RSA 加密
public string RsaEncrypt(string rawInput, string publicKey)
{
if (string.IsNullOrEmpty(rawInput))
{
return string.Empty;
}網絡
if(string.IsNullOrWhiteSpace(publicKey))
{
throw new ArgumentException("Invalid Public Key");
}框架
using (var rsaProvider = new RSACryptoServiceProvider())
{
var inputBytes = Encoding.UTF8.GetBytes(rawInput);//有含義的字符串轉化爲字節流
rsaProvider.FromXmlString(publicKey);//載入公鑰
int bufferSize = (rsaProvider.KeySize / 8) - 11;//單塊最大長度
var buffer = new byte[bufferSize];
using (MemoryStream inputStream = new MemoryStream(inputBytes),
outputStream = new MemoryStream())
{
while (true)
{ //分段加密
int readSize = inputStream.Read(buffer, 0, bufferSize);
if (readSize <= 0)
{
break;
}ide
var temp = new byte[readSize];
Array.Copy(buffer, 0, temp, 0, readSize);
var encryptedBytes = rsaProvider.Encrypt(temp, false);
outputStream.Write(encryptedBytes, 0, encryptedBytes.Length);
}
return Convert.ToBase64String(outputStream.ToArray());//轉化爲字節流方便傳輸
}
}
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
RSA 解密
public string RsaDecrypt(string encryptedInput, string privateKey)
{
if (string.IsNullOrEmpty(encryptedInput))
{
return string.Empty;
}學習
if (string.IsNullOrWhiteSpace(privateKey))
{
throw new ArgumentException("Invalid Private Key");
}優化
using (var rsaProvider = new RSACryptoServiceProvider())
{
var inputBytes = Convert.FromBase64String(encryptedInput);
rsaProvider.FromXmlString(privateKey);
int bufferSize = rsaProvider.KeySize / 8;
var buffer = new byte[bufferSize];
using (MemoryStream inputStream = new MemoryStream(inputBytes),
outputStream = new MemoryStream())
{
while (true)
{
int readSize = inputStream.Read(buffer, 0, bufferSize);
if (readSize <= 0)
{
break;
}加密
var temp = new byte[readSize];
Array.Copy(buffer, 0, temp, 0, readSize);
var rawBytes = rsaProvider.Decrypt(temp, false);
outputStream.Write(rawBytes, 0, rawBytes.Length);
}
return Encoding.UTF8.GetString(outputStream.ToArray());
}
}
}
字符串