001/* 002 * Copyright 2015-2020 the original author or authors 003 * 004 * This software is licensed under the Apache License, Version 2.0, 005 * the GNU Lesser General Public License version 2 or later ("LGPL") 006 * and the WTFPL. 007 * You may choose either license to govern your use of this software only 008 * upon the condition that you accept all of the terms of either 009 * the Apache License 2.0, the LGPL 2.1+ or the WTFPL. 010 */ 011package org.minidns.dane; 012 013import javax.net.ssl.X509TrustManager; 014import java.security.cert.CertificateException; 015import java.security.cert.X509Certificate; 016 017public class ExpectingTrustManager implements X509TrustManager { 018 private CertificateException exception; 019 private final X509TrustManager trustManager; 020 021 /** 022 * Creates a new instance of ExpectingTrustManager. 023 * 024 * @param trustManager The {@link X509TrustManager} to be used for verification. 025 * {@code null} to use the system default. 026 */ 027 public ExpectingTrustManager(X509TrustManager trustManager) { 028 this.trustManager = trustManager == null ? X509TrustManagerUtil.getDefault() : trustManager; 029 } 030 031 public boolean hasException() { 032 return exception != null; 033 } 034 035 public CertificateException getException() { 036 CertificateException e = exception; 037 exception = null; 038 return e; 039 } 040 041 @Override 042 public void checkClientTrusted(X509Certificate[] chain, String authType) throws CertificateException { 043 try { 044 trustManager.checkClientTrusted(chain, authType); 045 } catch (CertificateException e) { 046 exception = e; 047 } 048 } 049 050 @Override 051 public void checkServerTrusted(X509Certificate[] chain, String authType) throws CertificateException { 052 try { 053 trustManager.checkServerTrusted(chain, authType); 054 } catch (CertificateException e) { 055 exception = e; 056 } 057 } 058 059 @Override 060 public X509Certificate[] getAcceptedIssuers() { 061 return trustManager.getAcceptedIssuers(); 062 } 063}