C#数字签名 SHA256withRSA
#region 公钥验签/// <summary>
/// 公钥验签
/// </summary>
/// <param name="sign">签名</param>
/// <param name="content">明文</param>
/// <param name="publicKey">公钥</param>
/// <returns></returns>
static bool PublicKeyVerifySign(string sign, string content, string publicKey)
{
try
{
//.net core2.2及其以下版本使用,重写FromXmlString(string)方法
RSACryptoServiceProvider rsa = new RSACryptoServiceProvider();
rsa.FromXmlString(publicKey);
byte[] signature = Convert.FromBase64String(sign);
SHA256Managed sha256 = new SHA256Managed();
RSAPKCS1SignatureDeformatter df = new RSAPKCS1SignatureDeformatter(rsa);
df.SetHashAlgorithm("SHA256");
byte[] compareByte = sha256.ComputeHash(Encoding.UTF8.GetBytes(content));
return df.VerifySignature(compareByte, signature);
}
catch (Exception)
{
return false;
}
}
#endregion
/// <summary>
/// RSA公钥格式转换,java->.net
/// </summary>
/// <param name="publicKey">java生成的公钥</param>
/// <returns></returns>
static string RSAPublicKeyJavaToDotNet(string publicKey)
{
RsaKeyParameters publicKeyParam = (RsaKeyParameters)PublicKeyFactory.CreateKey(Convert.FromBase64String(publicKey));
return string.Format("<RSAKeyValue><Modulus>{0}</Modulus><Exponent>{1}</Exponent></RSAKeyValue>",
Convert.ToBase64String(publicKeyParam.Modulus.ToByteArrayUnsigned()),
Convert.ToBase64String(publicKeyParam.Exponent.ToByteArrayUnsigned()));
}
/// <summary>
/// RSA私钥格式转换,java->.net
/// </summary>
/// <param name="privateKey">java生成的RSA私钥</param>
/// <returns></returns>
static string RSAPrivateKeyJavaToDotNet(string privateKey)
{
RsaPrivateCrtKeyParameters privateKeyParam = (RsaPrivateCrtKeyParameters)PrivateKeyFactory.CreateKey(Convert.FromBase64String(privateKey));
return string.Format("<RSAKeyValue><Modulus>{0}</Modulus><Exponent>{1}</Exponent><P>{2}</P><Q>{3}</Q><DP>{4}</DP><DQ>{5}</DQ><InverseQ>{6}</InverseQ><D>{7}</D></RSAKeyValue>",
Convert.ToBase64String(privateKeyParam.Modulus.ToByteArrayUnsigned()),
Convert.ToBase64String(privateKeyParam.PublicExponent.ToByteArrayUnsigned()),
Convert.ToBase64String(privateKeyParam.P.ToByteArrayUnsigned()),
Convert.ToBase64String(privateKeyParam.Q.ToByteArrayUnsigned()),
Convert.ToBase64String(privateKeyParam.DP.ToByteArrayUnsigned()),
Convert.ToBase64String(privateKeyParam.DQ.ToByteArrayUnsigned()),
Convert.ToBase64String(privateKeyParam.QInv.ToByteArrayUnsigned()),
Convert.ToBase64String(privateKeyParam.Exponent.ToByteArrayUnsigned()));
}
#region 私钥签名
/// <summary>
/// 私钥签名
/// </summary>
/// <param name="content"></param>
/// <returns></returns>
static string PrivateKeySign(string content, string privateKey)
{
var rsa = new RSACryptoServiceProvider();
rsa.FromXmlString(privateKey);
var rsaClear = new RSACryptoServiceProvider();
var paras = rsa.ExportParameters(true);
rsaClear.ImportParameters(paras);
using (var sha256 = new SHA256CryptoServiceProvider())
{
var signData = rsa.SignData(Encoding.UTF8.GetBytes(content), sha256);
return Convert.ToBase64String(signData);
}
}
#endregion
页:
[1]