Connect web service with SSL connection

1. Import the cert file
2. Import the pfx file
3.
程序代码 程序代码

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Net;
using System.Security.Cryptography.X509Certificates;
using System.Net.Security;
using ConsoleApplication1.ScsWebReference;

namespace ConsoleApplication1
{
    class Program
    {
        static string ServiceUrl = "https://172.22.120.154/scs/scsapiwebservice.asmx?wsdl";
        static string CertSerialNumber = "1fcf8092000000002d07";

        static void Main(string[] args)
        {
            ServicePointManager.ServerCertificateValidationCallback = (sender, certificate, chain, sslPolicyErrors) =>
            {
                if (sslPolicyErrors == SslPolicyErrors.RemoteCertificateNameMismatch || sslPolicyErrors == SslPolicyErrors.None)
                {
                    return true;
                }
                else
                {
                    return false;
                }
            };

            bdk scs = new bdk();
            scs.Url = ServiceUrl;
            scs.ClientCertificates.Add(GetCert(CertSerialNumber));

            string testConnectionOut;
            scs.TestConnection("Scs Test", out testConnectionOut);
        }

        private static X509Certificate GetCert(string serialNumber)
        {
            X509Store store = new X509Store(StoreName.My, StoreLocation.CurrentUser);
            store.Open(OpenFlags.OpenExistingOnly);
            try
            {
                foreach (X509Certificate2 cert in store.Certificates)
                {
                    if (cert.GetSerialNumberString().Equals(serialNumber, StringComparison.OrdinalIgnoreCase))
                    {
                        if (!cert.HasPrivateKey)
                        {
                            throw new ApplicationException("The cert (" + serialNumber + ") does not have a private key");
                        }

                        Console.Write("Got the cert, serial number:" + serialNumber);
                        return cert;
                    }
                }

                throw new ApplicationException("Cannot find cert with SN=" + serialNumber);
            }
            finally
            {
                store.Close();
            }
        }
    }
}



[本日志由 Peter 于 2010-07-05 01:53 PM 编辑]
文章来自: 本站原创
引用通告: 查看所有引用 | 我要引用此文章
Tags:
评论: 0 | 引用: 0 | 查看次数: 78
发表评论
昵 称:
密 码: 游客发言不需要密码.
验证码: 验证码
内 容:
选 项:
虽然发表评论不用注册,但是为了保护您的发言权,建议您注册帐号.
字数限制 1000 字 | UBB代码 开启 | [img]标签 关闭