这是一篇转载合并文章,主要内容来自一下两篇:
使用的库 bouncycastle
加密解密
加密解密相关的代码,见:
签名,验证签名
#region 加签
/// <summary>
/// 基于BouncyCastle的RSA签名
/// </summary>
/// <param name="data"></param>
/// <param name="privateKeyJava"></param>
/// <param name="hashAlgorithm">JAVA的和.NET的不一样,如:MD5(.NET)等同于MD5withRSA(JAVA)</param>
/// <param name="encoding"></param>
/// <returns></returns>
public static string RSASignJavaBouncyCastle(string data, string privateKeyJava, string hashAlgorithm = "MD5withRSA", string encoding = "UTF-8")
{
RsaKeyParameters privateKeyParam = (RsaKeyParameters)PrivateKeyFactory.CreateKey(Convert.FromBase64String(privateKeyJava));
ISigner signer = SignerUtilities.GetSigner(hashAlgorithm);
signer.Init(true, privateKeyParam);//参数为true验签,参数为false加签
var dataByte = Encoding.GetEncoding(encoding).GetBytes(data);
signer.BlockUpdate(dataByte, 0, dataByte.Length);
//return Encoding.GetEncoding(encoding).GetString(signer.GenerateSignature()); //签名结果 非Base64String
return Convert.ToBase64String(signer.GenerateSignature());
}
#endregion
#region 验签
/// <summary>
/// 基于BouncyCastle的RSA签名
/// </summary>
/// <param name="data">源数据</param>
/// <param name="publicKeyJava"></param>
/// <param name="signature">base64签名</param>
/// <param name="hashAlgorithm">JAVA的和.NET的不一样,如:MD5(.NET)等同于MD5withRSA(JAVA)</param>
/// <param name="encoding"></param>
/// <returns></returns>
public static bool VerifyJavaBouncyCastle(string data, string publicKeyJava, string signature, string hashAlgorithm = "MD5withRSA", string encoding = "UTF-8")
{
RsaKeyParameters publicKeyParam = (RsaKeyParameters)PublicKeyFactory.CreateKey(Convert.FromBase64String(publicKeyJava));
ISigner signer = SignerUtilities.GetSigner(hashAlgorithm);
signer.Init(false, publicKeyParam);
byte[] dataByte = Encoding.GetEncoding(encoding).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);
}
hash 算法如果使用 SHA256,则使用 SHA256withRSA
C# 原生自带的类,不支持 OpenSSL 生成的密钥。 rsa - C# 如何使用OpenSSL生成的公钥秘钥对进行加密解密? - SegmentFault 思否
END
原文链接:https://www.cnblogs.com/jasongrass/p/12871621.html
|
请发表评论