using System;
using System.Text;
using Org.BouncyCastle.Crypto.Parameters;
using Org.BouncyCastle.Security;
namespace MySystem
{
public class RSASignHelper
{
public readonly static RSASignHelper Instance = new RSASignHelper();
private RSASignHelper()
{
}
///
/// RSA签名
///
/// 数据
/// RSA密钥
///
public string RsaSign(string content, string privateKey)
{
var signer = SignerUtilities.GetSigner("SHA1withRSA");
//将java格式的rsa密钥转换成.net格式
var privateKeyParam = (RsaPrivateCrtKeyParameters)PrivateKeyFactory.CreateKey(Convert.FromBase64String(privateKey));
signer.Init(true, privateKeyParam);
var plainBytes = Encoding.UTF8.GetBytes(content);
signer.BlockUpdate(plainBytes, 0, plainBytes.Length);
var signBytes = signer.GenerateSignature();
return ByteToHexStr(signBytes);
}
///
/// RSA验签
///
/// 内容
/// RSA公钥
/// 签名字段
///
public bool VerifySign(string content, string publicKey, string signData)
{
try
{
var signer = SignerUtilities.GetSigner("SHA1withRSA");
var publicKeyParam = (RsaKeyParameters)PublicKeyFactory.CreateKey(StrToToHexByte(publicKey));
signer.Init(false, publicKeyParam);
var signBytes = StrToToHexByte(signData);
var plainBytes = Encoding.UTF8.GetBytes(content);
signer.BlockUpdate(plainBytes, 0, plainBytes.Length);
var ret = signer.VerifySignature(signBytes);
return ret;
}
catch (Exception ex)
{
return false;
}
}
///
/// 字符串转16进制字节数组
///
///
///
private byte[] StrToToHexByte(string hexString)
{
hexString = hexString.Replace(" ", "");
if ((hexString.Length % 2) != 0)
hexString += " ";
byte[] returnBytes = new byte[hexString.Length / 2];
for (int i = 0; i < returnBytes.Length; i++)
returnBytes[i] = Convert.ToByte(hexString.Substring(i * 2, 2), 16);
return returnBytes;
}
///
/// 字节数组转16进制字符串
///
///
///
public string ByteToHexStr(byte[] bytes)
{
string returnStr = "";
if (bytes != null)
{
for (int i = 0; i < bytes.Length; i++)
{
returnStr += bytes[i].ToString("X2");
}
}
return returnStr;
}
}
}