标签:init 私钥 ++ iba 加载 v2p [] from lse
看到网上 很多用C# 实现MD5WithRSA算法,都是使用的 证书,通过加载证书 和证书密码加密。
但是实际中,我们也有通过 密钥加密的情况,如是找了很久 终于找到方法,首先要下载一个 BouncyCastle.Crypto.dll 。
话不多说,贴代码:
public class md5withRsa
{
public static Encoding encoding = Encoding.GetEncoding("GBK");
public static string SignerSymbol = "MD5withRSA";
public md5withRsa() { }
public md5withRsa(Encoding e, string s)
{
encoding = e;
SignerSymbol = s;
}
private static AsymmetricKeyParameter CreateKEY(bool isPrivate, string key)
{
byte[] keyInfoByte = Convert.FromBase64String(key);
if (isPrivate)
return PrivateKeyFactory.CreateKey(keyInfoByte);
else
return PublicKeyFactory.CreateKey(keyInfoByte);
}
/// <summary>
/// 数据加密
/// </summary>
/// <param name="content">待加密字符串</param>
/// <param name="privatekey">私钥</param>
/// <returns>加密后字符串</returns>
public static string Sign(string content, string privatekey)
{
ISigner sig = SignerUtilities.GetSigner(SignerSymbol);
sig.Init(true, CreateKEY(true, privatekey));
var bytes = encoding.GetBytes(content);
sig.BlockUpdate(bytes, 0, bytes.Length);
byte[] signature = sig.GenerateSignature();
/* Base 64 encode the sig so its 8-bit clean */
var signedString = Convert.ToBase64String(signature);
return signedString;
}
/// <summary>
/// 验证签名
/// </summary>
/// <param name="content">待签名的字符串</param>
/// <param name="signData">加密后的文本</param>
/// <param name="publickey">公钥文本</param>
/// <returns>是否一致</returns>
public static bool Verify(string content, string signData, string publickey)
{
ISigner signer = SignerUtilities.GetSigner(SignerSymbol);
signer.Init(false, CreateKEY(false, publickey));
var expectedSig = Convert.FromBase64String(signData);
/* Get the bytes to be signed from the string */
var msgBytes = encoding.GetBytes(content);
/* Calculate the signature and see if it matches */
signer.BlockUpdate(msgBytes, 0, msgBytes.Length);
return signer.VerifySignature(expectedSig);
}
}
这样,我们 通过 Sign() 方法加密,通过Verify()方法验证签名即可。
这里提供一组数据给大家验证:
私钥:MIICdQIBADANBgkqhkiG9w0BAQEFA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7WCyrn3LgYpG52f0TVbj1palYwD1y7YI+VJJ+G4xfTvtaXZ7cWCAbTH8j/8WwGUjyJpG5vDkKJzkD8JR1YADaAGMsL43Weeeovj+FjDHt/vLtkJ8cHnJAxAgIilFCENf9X8XlMGbvH2tJ0mYhZat55U=
还有一个可以在线进行 md5withRsa 加密验签的网站:www.yunsos.com/Md5WithRSA.aspx 可以在线验证。
希望能够帮到大家!
标签:init 私钥 ++ iba 加载 v2p [] from lse
原文地址:https://www.cnblogs.com/yunsos/p/9040915.html