c#RSA 私钥加签公钥解签

/// RSA签名
/// </summary>
/// <param name="data">待签名数据</param>
/// <param name="privateKeyJava"></param>
/// <returns></returns>
public static string RSASignBouncyCastle(string data, string privateKeyJava)
{
RsaKeyParameters privateKeyParam = (RsaKeyParameters)PrivateKeyFactory.CreateKey(Convert.FromBase64String(privateKeyJava));
ISigner signer = SignerUtilities.GetSigner("SHA1WithRSA");
signer.Init(true, privateKeyParam);//参数为true加签,参数为false验签
var dataByte = Encoding.GetEncoding("UTF-8").GetBytes(data);
signer.BlockUpdate(dataByte, 0, dataByte.Length);
// return Encoding.GetEncoding("UTF-8").GetString(signer.GenerateSignature()); //签名结果 非Base64String
return Convert.ToBase64String(signer.GenerateSignature());
}
/// <summary>
/// 验签
/// </summary>
/// <param name="data">源数据</param>
/// <param name="publicKey"></param>
/// <param name="signature">base64签名</param>
/// <returns></returns>
public static bool VerifyBouncyCastle(string data, string publicKey, string signature)
{
RsaKeyParameters publicKeyParam = (RsaKeyParameters)PublicKeyFactory.CreateKey(Convert.FromBase64String(publicKey));
ISigner signer = SignerUtilities.GetSigner("SHA1WithRSA");
signer.Init(false, publicKeyParam);
byte[] dataByte = Encoding.GetEncoding("UTF-8").GetBytes(data);
signer.BlockUpdate(dataByte, 0, dataByte.Length);
//byte[] signatureByte = Encoding.GetEncoding(encoding).GetBytes(signature);// 非Base64String
byte[] signatureByte = Convert.FromBase64String(signature);
return signer.VerifySignature(signatureByte);
}

posted @ 2018-07-26 10:07  咬轮猫  阅读(1042)  评论(0编辑  收藏  举报
Live2D