加密和解密之非对称加密
public class RSACSProviderSecurity
{
/// <summary>
/// 密钥,时间戳
/// 密钥+时间戳=明文签名
/// </summary>
#region 公钥加密方法
public static string EncryptRSACSPSecurity(string key, string timestamp, string publickey, Encoding encoding = default(Encoding))
{
if (string.IsNullOrEmpty(key))
{
throw new ArgumentNullException("key");
}
if (string.IsNullOrEmpty(timestamp))
{
throw new ArgumentNullException("timestamp");
}
encoding = encoding ?? Encoding.UTF8;
string plainText = string.Format("key={0}×tamp={1}", key, timestamp);
byte[] plainData = encoding.GetBytes(plainText);
byte[] cipherData =Encrypt(plainData,publickey);
return Convert.ToBase64String(cipherData);
}
private static byte[] Encrypt(byte[] plainText, string xmlPublicKey)
{
if (plainText == null)
{
throw new ArgumentNullException("plainText");
}
RSACryptoServiceProvider rsaCryptoServiceProvider = new RSACryptoServiceProvider();
rsaCryptoServiceProvider.FromXmlString(xmlPublicKey);
return rsaCryptoServiceProvider.Encrypt(plainText, true);
}
#endregion
#region 私钥解密方法
public static bool DecryptRSACSPSecurity(string key, string timestamp, string base64Signature, string privateKey, Encoding encoding = default(Encoding))
{
if (string.IsNullOrEmpty(key))
{
return false;
}
if (string.IsNullOrEmpty(timestamp))
{
return false;
}
if (string.IsNullOrEmpty(base64Signature))
{
return false;
}
encoding = encoding ?? Encoding.UTF8;
byte[] cipherData = Convert.FromBase64String(base64Signature);
byte[] plainData = Decrypt(cipherData,privateKey);
string plainSignature = encoding.GetString(plainData);
string signature = string.Format("key={0}×tamp={1}", key, timestamp);
return plainSignature == signature;
}
private static byte[] Decrypt(byte[] cipherText, string xmlPrivateKey)
{
if (cipherText == null)
{
throw new ArgumentNullException("cipherText");
}
RSACryptoServiceProvider rsaCryptoServiceProvider = new RSACryptoServiceProvider();
rsaCryptoServiceProvider.FromXmlString(xmlPrivateKey);
return rsaCryptoServiceProvider.Decrypt(cipherText, true);
}
}
#region 生成公钥或者私钥
//RSACryptoServiceProvider oRSA = new RSACryptoServiceProvider();
//string privatekey = oRSA.ToXmlString(true);//私钥
//string publickey = oRSA.ToXmlString(false);//公钥
#endregion