现在的位置: 首页 > 综合 > 正文

java,C#,C++ 中SSL 连接信任所有证书.

2013年12月12日 ⁄ 综合 ⁄ 共 11413字 ⁄ 字号 评论关闭

通过SSL跟服务器做连接的时候,一般需要预先导入服务器证书.否则在建议连接时,会失败,那么怎么样自动信任所有证书呢?以下分别是Java,C#,C++的实现代码:

================================ java  ===================

  1. package cn.net.drm.encryptInterface;
  2. import java.security.GeneralSecurityException;
  3. import java.security.SecureRandom;
  4. import java.security.cert.X509Certificate;
  5. import javax.net.ssl.HostnameVerifier;
  6. import javax.net.ssl.HttpsURLConnection;
  7. import javax.net.ssl.SSLContext;
  8. import javax.net.ssl.TrustManager;
  9. import javax.net.ssl.X509TrustManager;
  10. /**
  11.  * This class provide various static methods that relax X509 certificate and
  12.  * hostname verification while using the SSL over the HTTP protocol.
  13.  *
  14.  * @author    Francis Labrie
  15.  */
  16. public final class SSLUtils {
  17.   /**
  18.    * Hostname verifier for the Sun's deprecated API.
  19.    */
  20.   private static com.sun.net.ssl.HostnameVerifier __hostnameVerifier;
  21.   /**
  22.    * Thrust managers for the Sun's deprecated API.
  23.    */
  24.   private static com.sun.net.ssl.TrustManager[] __trustManagers;
  25.   /**
  26.    * Hostname verifier.
  27.    */
  28.   private static HostnameVerifier _hostnameVerifier;
  29.   /**
  30.    * Thrust managers.
  31.    */
  32.   private static TrustManager[] _trustManagers;
  33.   /**
  34.    * Set the default Hostname Verifier to an instance of a fake class that
  35.    * trust all hostnames. This method uses the old deprecated API from the
  36.    * <code>com.sun.ssl</code> package.
  37.    *
  38.    */
  39.   private static void __trustAllHostnames() {
  40.       // Create a trust manager that does not validate certificate chains
  41.       if(__hostnameVerifier == null) {
  42.           __hostnameVerifier = new _FakeHostnameVerifier();
  43.       } // if
  44.       // Install the all-trusting host name verifier
  45.       com.sun.net.ssl.HttpsURLConnection.
  46.           setDefaultHostnameVerifier(__hostnameVerifier);
  47.   } // __trustAllHttpsCertificates
  48.   /**
  49.    * Set the default X509 Trust Manager to an instance of a fake class that
  50.    * trust all certificates, even the self-signed ones. This method uses the
  51.    * old deprecated API from the <code>com.sun.ssl</code> package.
  52.    *
  53.    * @deprecated see {@link #_trustAllHttpsCertificates()}.
  54.    */
  55.   private static void __trustAllHttpsCertificates() {
  56.       com.sun.net.ssl.SSLContext context;
  57.       // Create a trust manager that does not validate certificate chains
  58.       if(__trustManagers == null) {
  59.           __trustManagers = new com.sun.net.ssl.TrustManager[]
  60.               {new _FakeX509TrustManager()};
  61.       } // if
  62.       // Install the all-trusting trust manager
  63.       try {
  64.           context = com.sun.net.ssl.SSLContext.getInstance("SSL");
  65.           context.init(null, __trustManagers, new SecureRandom());
  66.       } catch(GeneralSecurityException gse) {
  67.           throw new IllegalStateException(gse.getMessage());
  68.       } // catch
  69.       com.sun.net.ssl.HttpsURLConnection.
  70.           setDefaultSSLSocketFactory(context.getSocketFactory());
  71.   } // __trustAllHttpsCertificates
  72.   /**
  73.    * Return <code>true</code> if the protocol handler property <code>java.
  74.    * protocol.handler.pkgs</code> is set to the Sun's <code>com.sun.net.ssl.
  75.    * internal.www.protocol</code> deprecated one, <code>false</code>
  76.    * otherwise.
  77.    *
  78.    * @return                <code>true</code> if the protocol handler
  79.    * property is set to the Sun's deprecated one, <code>false</code>
  80.    * otherwise.
  81.    */
  82.   private static boolean isDeprecatedSSLProtocol() {
  83.       return("com.sun.net.ssl.internal.www.protocol".equals(System.
  84.           getProperty("java.protocol.handler.pkgs")));
  85.   } // isDeprecatedSSLProtocol
  86.   /**
  87.    * Set the default Hostname Verifier to an instance of a fake class that
  88.    * trust all hostnames.
  89.    */
  90.   private static void _trustAllHostnames() {
  91.       // Create a trust manager that does not validate certificate chains
  92.       if(_hostnameVerifier == null) {
  93.           _hostnameVerifier = new FakeHostnameVerifier();
  94.       } // if
  95.         // Install the all-trusting host name verifier:
  96.       HttpsURLConnection.setDefaultHostnameVerifier(_hostnameVerifier);
  97.   } // _trustAllHttpsCertificates
  98.   /**
  99.    * Set the default X509 Trust Manager to an instance of a fake class that
  100.    * trust all certificates, even the self-signed ones.
  101.    */
  102.   private static void _trustAllHttpsCertificates() {
  103.       SSLContext context;
  104.       // Create a trust manager that does not validate certificate chains
  105.       if(_trustManagers == null) {
  106.           _trustManagers = new TrustManager[] {new FakeX509TrustManager()};
  107.       } // if
  108.       // Install the all-trusting trust manager:
  109.       try {
  110.       context = SSLContext.getInstance("SSL");
  111.       context.init(null, _trustManagers, new SecureRandom());
  112.       } catch(GeneralSecurityException gse) {
  113.           throw new IllegalStateException(gse.getMessage());
  114.       } // catch
  115.       HttpsURLConnection.setDefaultSSLSocketFactory(context.
  116.           getSocketFactory());
  117.   } // _trustAllHttpsCertificates
  118.   /**
  119.    * Set the default Hostname Verifier to an instance of a fake class that
  120.    * trust all hostnames.
  121.    */
  122.   public static void trustAllHostnames() {
  123.       // Is the deprecated protocol setted?
  124.       if(isDeprecatedSSLProtocol()) {
  125.           __trustAllHostnames();
  126.       } else {
  127.           _trustAllHostnames();
  128.       } // else
  129.   } // trustAllHostnames
  130.   /**
  131.    * Set the default X509 Trust Manager to an instance of a fake class that
  132.    * trust all certificates, even the self-signed ones.
  133.    */
  134.   public static void trustAllHttpsCertificates() {
  135.       // Is the deprecated protocol setted?
  136.       if(isDeprecatedSSLProtocol()) {
  137.           __trustAllHttpsCertificates();
  138.       } else {
  139.           _trustAllHttpsCertificates();
  140.       } // else
  141.   } // trustAllHttpsCertificates
  142.   /**
  143.    * This class implements a fake hostname verificator, trusting any host
  144.    * name. This class uses the old deprecated API from the <code>com.sun.
  145.    * ssl</code> package.
  146.    *
  147.    * @author    Francis Labrie
  148.    *
  149.    * @deprecated see {@link SSLUtilities.FakeHostnameVerifier}.
  150.    */
  151.   public static class _FakeHostnameVerifier
  152.       implements com.sun.net.ssl.HostnameVerifier {
  153.       /**
  154.        * Always return <code>true</code>, indicating that the host name is an
  155.        * acceptable match with the server's authentication scheme.
  156.        *
  157.        * @param hostname        the host name.
  158.        * @param session         the SSL session used on the connection to
  159.        * host.
  160.        * @return                the <code>true</code> boolean value
  161.        * indicating the host name is trusted.
  162.        */
  163.       public boolean verify(String hostname, String session) {
  164.           return(true);
  165.       } // verify
  166.   } // _FakeHostnameVerifier
  167.   /**
  168.    * This class allow any X509 certificates to be used to authenticate the
  169.    * remote side of a secure socket, including self-signed certificates. This
  170.    * class uses the old deprecated API from the <code>com.sun.ssl</code>
  171.    * package.
  172.    *
  173.    * @author    Francis Labrie
  174.    *
  175.    * @deprecated see {@link SSLUtilities.FakeX509TrustManager}.
  176.    */
  177.   public static class _FakeX509TrustManager
  178.       implements com.sun.net.ssl.X509TrustManager {
  179.       /**
  180.        * Empty array of certificate authority certificates.
  181.        */
  182.       private static final X509Certificate[] _AcceptedIssuers =
  183.           new X509Certificate[] {};
  184.       /**
  185.        * Always return <code>true</code>, trusting for client SSL
  186.        * <code>chain</code> peer certificate chain.
  187.        *
  188.        * @param chain           the peer certificate chain.
  189.        * @return                the <code>true</code> boolean value
  190.        * indicating the chain is trusted.
  191.        */
  192.       public boolean isClientTrusted(X509Certificate[] chain) {
  193.           return(true);
  194.       } // checkClientTrusted
  195.       /**
  196.        * Always return <code>true</code>, trusting for server SSL
  197.        * <code>chain</code> peer certificate chain.
  198.        *
  199.        * @param chain           the peer certificate chain.
  200.        * @return                the <code>true</code> boolean value
  201.        * indicating the chain is trusted.
  202.        */
  203.       public boolean isServerTrusted(X509Certificate[] chain) {
  204.           return(true);
  205.       } // checkServerTrusted
  206.       /**
  207.        * Return an empty array of certificate authority certificates which
  208.        * are trusted for authenticating peers.
  209.        *
  210.        * @return                a empty array of issuer certificates.
  211.        */
  212.       public X509Certificate[] getAcceptedIssuers() {
  213.           return(_AcceptedIssuers);
  214.       } // getAcceptedIssuers
  215.   } // _FakeX509TrustManager
  216.   /**
  217.    * This class implements a fake hostname verificator, trusting any host
  218.    * name.
  219.    *
  220.    * @author    Francis Labrie
  221.    */
  222.   public static class FakeHostnameVerifier implements HostnameVerifier {
  223.       /**
  224.        * Always return <code>true</code>, indicating that the host name is
  225.        * an acceptable match with the server's authentication scheme.
  226.        *
  227.        * @param hostname        the host name.
  228.        * @param session         the SSL session used on the connection to
  229.        * host.
  230.        * @return                the <code>true</code> boolean value
  231.        * indicating the host name is trusted.
  232.        */
  233.       public boolean verify(String hostname,
  234.           javax.net.ssl.SSLSession session) {
  235.           return(true);
  236.       } // verify
  237.   } // FakeHostnameVerifier
  238.   /**
  239.    * This class allow any X509 certificates to be used to authenticate the
  240.    * remote side of a secure socket, including self-signed certificates.
  241.    *
  242.    * @author    Francis Labrie
  243.    */
  244.   public static class FakeX509TrustManager implements X509TrustManager {
  245.       /**
  246.        * Empty array of certificate authority certificates.
  247.        */
  248.       private static final X509Certificate[] _AcceptedIssuers =
  249.           new X509Certificate[] {};
  250.       /**
  251.        * Always trust for client SSL <code>chain</code> peer certificate
  252.        * chain with any <code>authType</code> authentication types.
  253.        *
  254.        * @param chain           the peer certificate chain.
  255.        * @param authType        the authentication type based on the client
  256.        * certificate.
  257.        */
  258.       public void checkClientTrusted(X509Certificate[] chain,
  259.           String authType) {
  260.       } // checkClientTrusted
  261.       /**
  262.        * Always trust for server SSL <code>chain</code> peer certificate
  263.        * chain with any <code>authType</code> exchange algorithm types.
  264.        *
  265.        * @param chain           the peer certificate chain.
  266.        * @param authType        the key exchange algorithm used.
  267.        */
  268.       public void checkServerTrusted(X509Certificate[] chain,
  269.           String authType) {
  270.       } // checkServerTrusted
  271.       /**
  272.        * Return an empty array of certificate authority certificates which
  273.        * are trusted for authenticating peers.
  274.        *
  275.        * @return                a empty array of issuer certificates.
  276.        */
  277.       public X509Certificate[] getAcceptedIssuers() {
  278.           return(_AcceptedIssuers);
  279.       } // getAcceptedIssuers
  280.   } // FakeX509TrustManager
  281. // SSLUtilities

在建立连接前,调用 SSLUtils.trustAllHttpsCertificates(); 就可以了.

 

=========================== C# ======================================

  1. class   AcceptAllCertificatePolicy   :   System.Net.ICertificatePolicy   
  2. {   
  3.     public   bool   CheckValidationResult(System.Net.ServicePoint   srvPoint,   
  4.     System.Security.Cryptography.X509Certificates.X509Certificate  certificate,   WebRequest   request, int   certificateProblem)   
  5.     {   
  6.     
  7.     return   true;   
  8.     }   

同样在连接前调用: System.Net.ServicePointManager.CertificatePolicy = new AcceptAllCertificatePolicy();  就行了.

====================== C IXmlHttpRequest 例============================================

只需要在连接前设置一下:

int SXH_SERVER_CERT_IGNORE_ALL_SERVER_ERRORS = 13056

xmlHttp.SetOption(2, SXH_SERVER_CERT_IGNORE_ALL_SERVER_ERRORS);
注意这段代码,实际中,可能需要填写enum常量.自己在相关文件中找到就行了.

抱歉!评论已关闭.