今天应项目要求,做一非对称加密,看了microsoft的simple,并不能导出private 和 public key .当然,网上
这样的例子很多,可没找到关于如何导入导出key及byte[]与string 的相互转化(调用了很多直接转化的函数,转化的过程中会有乱码,导致加解密失败。
项目要求,生成一个private key 和 public key ,用 Public Key 加密,用Private key 解密,我是这样实现的,
希望对有这方面需求朋友的一个帮助.
源代码如下:
1.生成一对keys:
/// <summary>
/// generate private key and public key arr[0] for private key arr[1] for public key
/// </summary>
/// <returns></returns>
public static string[] GenerateKeys()
{
string[] sKeys = new String[2];
RSACryptoServiceProvider rsa = new RSACryptoServiceProvider();
sKeys[0] = rsa.ToXmlString(true);
sKeys[1] = rsa.ToXmlString(false);
return sKeys;
}
2.加密:
/// <summary>
/// RSA Encrypt
/// </summary>
/// <param name="sSource" >Source string</param>
/// <param name="sPublicKey" >public key</param>
/// <returns></returns>
public static string EncryptString(string sSource,string sPublicKey)
{
RSACryptoServiceProvider rsa = new RSACryptoServiceProvider();
string plaintext = sSource;
rsa.FromXmlString(sPublicKey);
byte[] cipherbytes;
byte[] byteEn = rsa.Encrypt(Encoding.UTF8.GetBytes("a"), false);
cipherbytes = rsa.Encrypt(Encoding.UTF8.GetBytes(plaintext), false);
StringBuilder sbString = new StringBuilder();
for (int i = 0; i < cipherbytes.Length; i++)
{
sbString.Append(cipherbytes[i] + ",");
}
3. 解密:
/// <summary>
/// RSA Decrypt
/// </summary>
/// <param name="sSource">Source string</param>
/// <param name="sPrivateKey">Private Key</param>
/// <returns></returns>
public static string DecryptString(String sSource, string sPrivateKey)
{
RSACryptoServiceProvider rsa = new RSACryptoServiceProvider();
rsa.FromXmlString(sPrivateKey);
byte[] byteEn = rsa.Encrypt(Encoding.UTF8.GetBytes("a"), false);
string[] sBytes = sSource.Split(',');
for (int j = 0; j < sBytes.Length; j++)
{
if (sBytes[j] != "")
{
byteEn[j] = Byte.Parse(sBytes[j]);
}
}
byte[] plaintbytes = rsa.Decrypt(byteEn, false);
return Encoding.UTF8.GetString(plaintbytes);
}
return sbString.ToString();
}