標籤:
這是很久以前的寫的一篇部落格了,今天把他重新找出來整理一下發布到部落格園
當時對接銀聯的時候搞了很久都沒搞出來,後來一個偶然的機會發現類似的一個代碼參考了一下終於弄好了
這段代碼主要是實現了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 MD5WithRSA11 {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 }else29 {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 }
C#實現MD5WITHRSA簽名