RSA公鑰加密算法是1977年由Ron Rivest、Adi Shamirh和LenAdleman在(美國麻省理工學院)開發的。RSA取名來自開發他們三者的名字。RSA是目前最有影響力的公鑰加密算法,它能夠抵抗到目前為止已知的所有密碼攻擊,已被ISO推薦為公鑰資料加密标準。RSA算法基于一個十分簡單的數論事實:将兩個大素數相乘十分容易,但那時想要對其乘積進行因式分解卻極其困難,是以可以将乘積公開作為加密密鑰。
RSA公開密鑰密碼體制。所謂的公開密鑰密碼體制就是使用不同的加密密鑰與解密密鑰,是一種“由已知加密密鑰推導出解密密鑰在計算上是不可行的”密碼體制
下面貼出C#使用RSA私鑰加密公鑰解密的改進代碼:
一開始使用得挺好,加密解密都正常,但當加密的資料超過了128byte,解密後偶爾會出現亂碼,解密失敗。
由于RSA算法單次加密隻能支援128byte的資料,如果資料長度超過128byte,就會被分割為幾段進行加密,最後把加密結果轉換為16進制字元串,并連接配接起來輸出結果。
加密方法的改進:
由于加密後的結果是通過輸入16進制字元串進行儲存的,輸入的結果不可能包含@字元,是以我們可以用@符号來分割每128byte資料的加密結果,解密的時候按照@符号進行分割就不會出錯。
完整代碼:
public static class RSAHelper
{
/// <summary>
/// RSA的容器 可以解密的源字元串長度為 DWKEYSIZE/8-11
/// </summary>
public const int DWKEYSIZE = 1024;
/// <summary>
/// RSA加密的密匙結構 公鑰和私匙
/// </summary>
public struct RSAKey
{
public string PublicKey { get; set; }
public string PrivateKey { get; set; }
}
#region 得到RSA的解謎的密匙對
/// <summary>
/// 得到RSA的解謎的密匙對
/// </summary>
/// <returns></returns>
public static RSAKey GetRASKey()
{
RSACryptoServiceProvider.UseMachineKeyStore = true;
//聲明一個指定大小的RSA容器
RSACryptoServiceProvider rsaProvider = new RSACryptoServiceProvider(DWKEYSIZE);
//取得RSA容易裡的各種參數
RSAParameters p = rsaProvider.ExportParameters(true);
return new RSAKey()
{
PublicKey = ComponentKey(p.Exponent, p.Modulus),
PrivateKey = ComponentKey(p.D, p.Modulus)
};
}
#endregion
#region 檢查明文的有效性 DWKEYSIZE/8-11 長度之内為有效 中英文都算一個字元
/// <summary>
/// 檢查明文的有效性 DWKEYSIZE/8-11 長度之内為有效 中英文都算一個字元
/// </summary>
/// <param name="source"></param>
/// <returns></returns>
public static bool CheckSourceValidate(string source)
{
return (DWKEYSIZE / 8 - 11) >= source.Length;
}
#endregion
#region 組合解析密匙
/// <summary>
/// 組合成密匙字元串
/// </summary>
/// <param name="b1"></param>
/// <param name="b2"></param>
/// <returns></returns>
private static string ComponentKey(byte[] b1, byte[] b2)
{
List<byte> list = new List<byte>();
//在前端加上第一個數組的長度值 這樣今後可以根據這個值分别取出來兩個數組
list.Add((byte)b1.Length);
list.AddRange(b1);
list.AddRange(b2);
byte[] b = list.ToArray<byte>();
return Convert.ToBase64String(b);
}
/// <summary>
/// 解析密匙
/// </summary>
/// <param name="key">密匙</param>
/// <param name="b1">RSA的相應參數1</param>
/// <param name="b2">RSA的相應參數2</param>
private static void ResolveKey(string key, out byte[] b1, out byte[] b2)
{
//從base64字元串 解析成原來的位元組數組
byte[] b = Convert.FromBase64String(key);
//初始化參數的數組長度
b1 = new byte[b[0]];
b2 = new byte[b.Length - b[0] - 1];
//将相應位置是值放進相應的數組
for (int n = 1, i = 0, j = 0; n < b.Length; n++)
{
if (n <= b[0])
{
b1[i++] = b[n];
}
else
{
b2[j++] = b[n];
}
}
}
#endregion
#region 字元串加密解密 公開方法
/// <summary>
/// 字元串加密
/// </summary>
/// <param name="source">源字元串 明文</param>
/// <param name="key">密匙</param>
/// <returns>加密遇到錯誤将會傳回原字元串</returns>
public static string EncryptString(string source, string key)
{
string encryptString = string.Empty;
byte[] d;
byte[] n;
try
{
if (!CheckSourceValidate(source))
{
throw new Exception("source string too long");
}
//解析這個密鑰
ResolveKey(key, out d, out n);
BigInteger biN = new BigInteger(n);
BigInteger biD = new BigInteger(d);
encryptString = EncryptString(source, biD, biN);
}
catch
{
encryptString = source;
}
return encryptString;
}
/// <summary>
/// 字元串解密
/// </summary>
/// <param name="encryptString">密文</param>
/// <param name="key">密鑰</param>
/// <returns>遇到解密失敗将會傳回原字元串</returns>
public static string DecryptString(string encryptString, string key)
{
string source = string.Empty;
byte[] e;
byte[] n;
try
{
//解析這個密鑰
ResolveKey(key, out e, out n);
BigInteger biE = new BigInteger(e);
BigInteger biN = new BigInteger(n);
source = DecryptString(encryptString, biE, biN);
}
catch
{
source = encryptString;
}
return source;
}
#endregion
#region 字元串加密解密 私有 實作加解密的實作方法
/// <summary>
/// 用指定的密匙加密
/// </summary>
/// <param name="source">明文</param>
/// <param name="d">可以是RSACryptoServiceProvider生成的D</param>
/// <param name="n">可以是RSACryptoServiceProvider生成的Modulus</param>
/// <returns>傳回密文</returns>
public static string EncryptString(string source, BigInteger d, BigInteger n)
{
int len = source.Length;
int len1 = 0;
int blockLen = 0;
if ((len % 128) == 0)
len1 = len / 128;
else
len1 = len / 128 + 1;
string block = "";
StringBuilder result = new StringBuilder();
for (int i = 0; i < len1; i++)
{
if (len >= 128)
blockLen = 128;
else
blockLen = len;
block = source.Substring(i * 128, blockLen);
byte[] oText = System.Text.Encoding.Default.GetBytes(block);
BigInteger biText = new BigInteger(oText);
BigInteger biEnText = biText.modPow(d, n);
string temp = biEnText.ToHexString();
result.Append(temp).Append("@");
len -= blockLen;
}
return result.ToString().TrimEnd('@');
}
/// <summary>
/// 用指定的密匙加密
/// </summary>
/// <param name="source">密文</param>
/// <param name="e">可以是RSACryptoServiceProvider生成的Exponent</param>
/// <param name="n">可以是RSACryptoServiceProvider生成的Modulus</param>
/// <returns>傳回明文</returns>
public static string DecryptString(string encryptString, BigInteger e, BigInteger n)
{
StringBuilder result = new StringBuilder();
string[] strarr1 = encryptString.Split(new char[] { '@' }, StringSplitOptions.RemoveEmptyEntries);
for (int i = 0; i < strarr1.Length; i++)
{
string block = strarr1[i];
BigInteger biText = new BigInteger(block, 16);
BigInteger biEnText = biText.modPow(e, n);
string temp = System.Text.Encoding.Default.GetString(biEnText.getBytes());
result.Append(temp);
}
return result.ToString();
}
#endregion
}