C#在Linux+Mono環境中使用微信支付證書


最近特殊的需求,要把微信平台一個功能頁面部署到Linux(CentOS6.5)下,其中涉及到微信支付退款。

鑒於之前實踐過mono+jexus+asp.net mvc的部署,於是問題重點在於解決對商戶證書的調用問題。

 

查看微信支付官方文檔關於證書的使用說明

  • ◆ apiclient_cert.p12是商戶證書文件,除PHP外的開發均使用此證書文件。
  • ◆ 商戶如果使用.NET環境開發,請確認Framework版本大於2.0,必須在操作系統上雙擊安裝證書apiclient_cert.p12后才能被正常調用。
  • ◆ 商戶證書調用或安裝都需要使用到密碼,該密碼的值為微信商戶號(mch_id)
  • ◆ PHP開發環境請使用商戶證書文件apiclient_cert.pem和apiclient_key.pem ,rootca.pem是CA證書。

 

1.使用mono自帶工具certmgr導入.p12證書

certmgr -add -c -m -p 密碼 My ApiClient_cert.p12

2.編寫測試程序

using System;
using System.IO;
using System.Net;
using System.Net.Security;
using System.Security.Cryptography.X509Certificates;

public class TlsTest
{
    public static void Main(string[] args)
    {

        HttpWebResponse webreponse;
        string strHtml = "NO";
        try
        {
            //系統必須已經導入cert指向的證書
            string url = "https://api.mch.weixin.qq.com/secapi/pay/refund";
//My即對應”個人“存儲區,固定不可改變 X509Store store
= new X509Store("My", StoreLocation.LocalMachine); store.Open(OpenFlags.ReadOnly | OpenFlags.OpenExistingOnly); X509Certificate cer = store.Certificates.Find(X509FindType.FindByThumbprint, "546FCAA50DB599C5439AC8139C69393D5DB243D0", false)[0]; //遍歷證書查看Hash;windows下可直接雙擊安裝,查看屬性 //Console.WriteLine(store.Certificates.Count); //foreach(var c in store.Certificates){ // //Console.WriteLine("{0},{1},{2},{3},{4},{5}", c.GetCertHashString(), c.FriendlyName, c.GetFormat(), c.IssuerName, c.SubjectName, c.Thumbprint); // if (c.GetCertHashString() == "546FCAA50DB599C5439AC8139C69393D5DB243D0") // { // Console.WriteLine("found"); // cer = c; // break; // } //} HttpWebRequest webrequest = (HttpWebRequest)HttpWebRequest.Create(url); webrequest.ClientCertificates.Add(cer); webrequest.Method = "post"; webrequest.KeepAlive = true; webreponse = (HttpWebResponse)webrequest.GetResponse(); Stream stream = webreponse.GetResponseStream(); string resp = string.Empty; using (StreamReader reader = new StreamReader(stream)) { resp = reader.ReadToEnd(); } strHtml = resp; } catch (Exception exp) { strHtml = exp.ToString(); } Console.WriteLine(strHtml); } }

3.運行測試程序

mono SSLtest.exe

結果運行報錯

System.Net.WebException: Error: TrustFailure (The authentication or decryption has failed.) ---> System.IO.IOException: The authentication or decryption has failed. ---> System.IO.IOException: The authentication or decryption has failed. ---> Mono.Security.Protocol.Tls.TlsException: Invalid certificate received from server. Error code: 0xffffffff800b0109
  at Mono.Security.Protocol.Tls.RecordProtocol.EndReceiveRecord (IAsyncResult asyncResult) <0x40713980 + 0x0013e> in <filename unknown>:0 
  at Mono.Security.Protocol.Tls.SslClientStream.SafeEndReceiveRecord (IAsyncResult ar, Boolean ignoreEmpty) <0x407138b0 + 0x00031> in <filename unknown>:0 
  at Mono.Security.Protocol.Tls.SslClientStream.NegotiateAsyncWorker (IAsyncResult result) <0x4070d2d0 + 0x0023a> in <filename unknown>:0 
  --- End of inner exception stack trace ---
  at Mono.Security.Protocol.Tls.SslClientStream.EndNegotiateHandshake (IAsyncResult result) <0x40726300 + 0x000f3> in <filename unknown>:0 
  at Mono.Security.Protocol.Tls.SslStreamBase.AsyncHandshakeCallback (IAsyncResult asyncResult) <0x40726050 + 0x00086> in <filename unknown>:0 
  --- End of inner exception stack trace ---
  at Mono.Security.Protocol.Tls.SslStreamBase.EndRead (IAsyncResult asyncResult) <0x4070a990 + 0x00199> in <filename unknown>:0 
  at Mono.Net.Security.Private.LegacySslStream.EndAuthenticateAsClient (IAsyncResult asyncResult) <0x4070a8f0 + 0x00042> in <filename unknown>:0 
  at Mono.Net.Security.Private.LegacySslStream.AuthenticateAsClient (System.String targetHost, System.Security.Cryptography.X509Certificates.X509CertificateCollection clientCertificates, SslProtocols enabledSslProtocols, Boolean checkCertificateRevocation) <0x40704650 + 0x00055> in <filename unknown>:0 
  at Mono.Net.Security.MonoTlsStream.CreateStream (System.Byte[] buffer) <0x40703e00 + 0x00145> in <filename unknown>:0 
  --- End of inner exception stack trace ---
  at System.Net.HttpWebRequest.EndGetResponse (IAsyncResult asyncResult) <0x406fcf50 + 0x001ed> in <filename unknown>:0 
  at System.Net.HttpWebRequest.GetResponse () <0x406f5210 + 0x00053> in <filename unknown>:0 
  at TlsTest.Main (System.String[] args) <0x406a7d80 + 0x002c6> in <filename unknown>:0

 

4.發現錯誤原因是"Invalid certificate received from server",這個問題在Mono文檔中已有說明:

That’s probably because you do not trust the site you are connecting to. Note that a default installation of Mono doesn’t trust anyone!

默認情況下,任何站點都不被Mono信任!

同時也給出了4個解決方案:

  • 使用cert-sync工具同步Mono和系統的證書存儲區
  • 程序實現ICertificatePolicy自行決定信任規則
  • 使用certmgr.exe導入受信證書
  • 使用mozroots.exe自動導入常用的可信根證書

 

5.嘗試解決方案2

ServicePointManager.ServerCertificateValidationCallback = new RemoteCertificateValidationCallback(CheckValidationResult);

private static bool CheckValidationResult(object sender, X509Certificate c, X509Chain chain, SslPolicyErrors errors)
{
      return true;
}

報錯問題雖然可以解決,但對所有情況均信任不是一個好的解決方法,根據X509Certificate c進行判斷理應可行,沒有再進一步探索

 

6.嘗試解決方案4

使用mozroots自動下載安裝常用的根證書

mozroots --import --sync

顯示成功導入100+根證書,重新執行測試程序仍然報錯。

這個結果一度使我認為此方法無效,但偶然在本地測試卻通過了。

 

對比發現生效的下載路徑是:

https://hg.mozilla.org/releases/mozilla-release/raw-file/default/security/nss/lib/ckfw/builtins/certdata.txt

而無效的下載路徑是:

http://mxr.mozilla.org/seamonkey/source/security/nss/lib/ckfw/builtins/certdata.txt?raw=1

於是手動下載文件並指定mozroots安裝指定的文件

wget https://hg.mozilla.org/releases/mozilla-release/raw-file/default/security/nss/lib/ckfw/builtins/certdata.txt
mozroots --import --sync --file certdata.txt

這時,執行測試程序運行正常

<xml><return_code><![CDATA[FAIL]]></return_code>
<return_msg><![CDATA[post數據為空]]></return_msg>
</xml>

 

7.總結

使用mozroots是解決問題的簡單方法,但由於mono版本問題會導致默認的下載文件並不有效

本地有效版本:mono 4.6.0.0,使用中已提示建議使用cert-sync [WARNING: mozroots is deprecated, please move to cert-sync instead.]

服務器版本:mono 4.4.1.0,默認下載文件無效,這不得不說是個坑。


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM