RSA签名验证

时间:2020-11-27 22:04:24
        /// <summary>
/// 验证签名
/// </summary>
/// <param name="content">待签名字符串</param>
/// <param name="signedString">POST过来的签名</param>
/// <param name="publicKey">公钥</param>
/// <param name="input_charset">编码格式</param>
/// <returns></returns>
public static bool verify(string content, string signedString, string publicKey, string input_charset)
{
bool result = false;
try
{
Encoding code = Encoding.GetEncoding(input_charset);
byte[] Data = code.GetBytes(content);
byte[] data = Convert.FromBase64String(signedString);
RSAParameters paraPub = ConvertFromPublicKey(publicKey);
RSACryptoServiceProvider rsaPub = new RSACryptoServiceProvider();
rsaPub.ImportParameters(paraPub); SHA1 sh = new SHA1CryptoServiceProvider();
result = rsaPub.VerifyData(Data, sh, data);
return result;
}
catch (Exception ex)
{
return false;
}
} #region 解析.net 生成的Pem
private static RSAParameters ConvertFromPublicKey(string pemFileConent)
{ byte[] keyData = Convert.FromBase64String(pemFileConent);
if (keyData.Length < )
{
throw new ArgumentException("pem file content is incorrect.");
}
byte[] pemModulus = new byte[];
byte[] pemPublicExponent = new byte[];
Array.Copy(keyData, , pemModulus, , );
Array.Copy(keyData, , pemPublicExponent, , );
RSAParameters para = new RSAParameters();
para.Modulus = pemModulus;
para.Exponent = pemPublicExponent;
return para;
}