C#实现MD5WITHRSA签名

这是很久以前的写的一篇博客了,今天把他重新找出来整理一下发布到博客园

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

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

希望可以帮到大家

 1 using System;
 2 using System.Collections.Generic;
 3 using System.Linq;
 4 using System.Text;
 5 using System.Security.Cryptography.X509Certificates;
 6 using System.Security.Cryptography;
 7 
 8 namespace MD5WithRSATest
 9 {
10     public class MD5WithRSA
11     {
12         private static char[] bcdLookup = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f' };
13 
14         /// <summary>
15         /// 返回MD5WithRSA的签名字符串
16         /// </summary>
17         /// <param name="fileName">pfx证书文件的路径</param>
18         /// <param name="password">pfx证书密码</param>
19         /// <param name="strdata">待签名字符串</param>
20         /// <param name="encoding">字符集,默认为ISO-8859-1</param>
21         /// <returns>返回MD5WithRSA的签名字符串</returns>
22         public static string SignData(string fileName, string password, string strdata, string encoding = "ISO-8859-1")
23         {
24             X509Certificate2 objx5092;
25             if (string.IsNullOrWhiteSpace(password))
26             {
27                 objx5092 = new X509Certificate2(fileName);
28             }else
29             {
30                 objx5092 = new X509Certificate2(fileName, password);
31             }
32             RSACryptoServiceProvider rsa = objx5092.PrivateKey as RSACryptoServiceProvider;
33             byte[] data = Encoding.GetEncoding(encoding).GetBytes(strdata);
34             byte[] hashvalue = rsa.SignData(data, "MD5");//为证书采用MD5withRSA 签名
35             return bytesToHexStr(hashvalue);///将签名结果转化为16进制字符串
36         }
37         /// <summary>
38         /// 将签名结果转化为16进制字符串
39         /// </summary>
40         /// <param name="bcd">签名结果的byte数字</param>
41         /// <returns>16进制字符串</returns>
42         private static string bytesToHexStr(byte[] bcd)
43         {
44             StringBuilder s = new StringBuilder(bcd.Length * 2);
45             for (int i = 0; i < bcd.Length; i++)
46             {
47                 s.Append(bcdLookup[(bcd[i] >> 4) & 0x0f]);
48                 s.Append(bcdLookup[bcd[i] & 0x0f]);
49             }
50             return s.ToString();
51         }
52     }
53 }

 

posted @ 2015-08-21 09:27  Draenei  阅读(6195)  评论(0编辑  收藏  举报