用自己的实现和信任管理器替换SSLContext默认值

时间:2016-02-18 17:52:15

标签: java ssl java-8

根据Jcs(HttpUnit WebConversation SSL Issues)的回答,我尝试用我自己的信任管理员替换SSLContext.getDefault()

SSLContext ssl = SSLContext.getDefault();
ssl.init(null, new X509TrustManager[]{new AnyTrustManager()}, null);
ssl.setDefault(ssl);

AnyTrustManager():

import java.security.cert.X509Certificate;
import javax.net.ssl.X509TrustManager;

public class AnyTrustManager implements X509TrustManager
{
  X509Certificate[] client = null;
  X509Certificate[] server = null;

  public void checkClientTrusted(X509Certificate[] chain, String authType)
  {
    client = chain;
  }

  public void checkServerTrusted(X509Certificate[] chain, String authType)
  {
    server = chain;
  }

  public X509Certificate[] getAcceptedIssuers()
  {
    return new X509Certificate[0];
  }
}

我需要这样做,因为第三方.jar只使用SSLContext默认值导致我出现一些问题所以在此操作的持续时间内我必须将默认值更改为其他内容并稍后将其更改回来。

不幸的是,这会抛出java.security.KeyManagementException: Default SSLContext is initialized automatically例外。

如何让它在Java 8上运行?

1 个答案:

答案 0 :(得分:3)

"默认" SSLContext是不可变的。因此,TrustManager实例是不可能的。相反,你应该替换

SSLContext ssl = SSLContext.getDefault();

by(例如)

SSLContext ssl = SSLContext.getInstance("TLSv1");