您的位置:首页 > 编程语言 > C#

C#实现MD5WITHRSA签名

2015-08-21 09:27 627 查看
这是很久以前的写的一篇博客了,今天把他重新找出来整理一下发布到博客园

当时对接银联的时候搞了很久都没搞出来,后来一个偶然的机会发现类似的一个代码参考了一下终于弄好了

这段代码主要是实现了C#服务端对接手机银联的java端的接口的签名

希望可以帮到大家

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Security.Cryptography.X509Certificates;
using System.Security.Cryptography;

namespace MD5WithRSATest
{
public class MD5WithRSA
{
private static char[] bcdLookup = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f' };

/// <summary>
/// 返回MD5WithRSA的签名字符串
/// </summary>
/// <param name="fileName">pfx证书文件的路径</param>
/// <param name="password">pfx证书密码</param>
/// <param name="strdata">待签名字符串</param>
/// <param name="encoding">字符集,默认为ISO-8859-1</param>
/// <returns>返回MD5WithRSA的签名字符串</returns>
public static string SignData(string fileName, string password, string strdata, string encoding = "ISO-8859-1")
{
X509Certificate2 objx5092;
if (string.IsNullOrWhiteSpace(password))
{
objx5092 = new X509Certificate2(fileName);
}else
{
objx5092 = new X509Certificate2(fileName, password);
}
RSACryptoServiceProvider rsa = objx5092.PrivateKey as RSACryptoServiceProvider;
byte[] data = Encoding.GetEncoding(encoding).GetBytes(strdata);
byte[] hashvalue = rsa.SignData(data, "MD5");//为证书采用MD5withRSA 签名
return bytesToHexStr(hashvalue);///将签名结果转化为16进制字符串
}
/// <summary>
/// 将签名结果转化为16进制字符串
/// </summary>
/// <param name="bcd">签名结果的byte数字</param>
/// <returns>16进制字符串</returns>
private static string bytesToHexStr(byte[] bcd)
{
StringBuilder s = new StringBuilder(bcd.Length * 2);
for (int i = 0; i < bcd.Length; i++)
{
s.Append(bcdLookup[(bcd[i] >> 4) & 0x0f]);
s.Append(bcdLookup[bcd[i] & 0x0f]);
}
return s.ToString();
}
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: