下面列出了java.security.cert.CertificateExpiredException#javax.net.ssl.X509TrustManager 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。
public X509TrustManagerWrapper(X509TrustManager tm, boolean verifyServerCertificate, String hostName) throws CertificateException {
this.origTm = tm;
this.verifyServerCert = verifyServerCertificate;
this.hostName = hostName;
if (verifyServerCertificate) {
try {
Set<TrustAnchor> anch = Arrays.stream(tm.getAcceptedIssuers()).map(c -> new TrustAnchor(c, null)).collect(Collectors.toSet());
this.validatorParams = new PKIXParameters(anch);
this.validatorParams.setRevocationEnabled(false);
this.validator = CertPathValidator.getInstance("PKIX");
this.certFactory = CertificateFactory.getInstance("X.509");
} catch (Exception e) {
throw new CertificateException(e);
}
}
}
/**
* Returns a new instance of the default TrustManager for this JVM. Uses the default JVM trust store, which is
* generally the cacerts file in JAVA_HOME/jre/lib/security, but this can be overridden using JVM parameters.
*/
public static X509TrustManager getDefaultJavaTrustManager() {
TrustManagerFactory tmf;
try {
tmf = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());
// initializing the trust store with a null KeyStore will load the default JVM trust store
tmf.init((KeyStore) null);
} catch (NoSuchAlgorithmException | KeyStoreException e) {
throw new TrustSourceException("Unable to retrieve default TrustManagerFactory", e);
}
// Get hold of the default trust manager
for (TrustManager tm : tmf.getTrustManagers()) {
if (tm instanceof X509TrustManager) {
return (X509TrustManager) tm;
}
}
// didn't find an X509TrustManager
throw new TrustSourceException("No X509TrustManager found");
}
public static KeyStore defaultKeyStore()
throws KeyStoreException, NoSuchAlgorithmException, CertificateException, FileNotFoundException, IOException {
final KeyStore defaultKeystore = KeyStore.getInstance(KeyStore.getDefaultType());
defaultKeystore.load(null);
final TrustManagerFactory factory = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());
factory.init((KeyStore) null);
for (final TrustManager manager : factory.getTrustManagers()) {
final X509TrustManager x509Manager = (X509TrustManager) manager;
final X509Certificate[] issuers = x509Manager.getAcceptedIssuers();
for (final X509Certificate issuer : issuers) {
final String alias = issuer.getSerialNumber().toString();
final TrustedCertificateEntry entry = new TrustedCertificateEntry(issuer);
defaultKeystore.setEntry(alias, entry, null);
}
}
return defaultKeystore;
}
public X509TrustManagerWrapper(X509TrustManager tm, boolean verifyServerCertificate, String hostName) throws CertificateException {
this.origTm = tm;
this.verifyServerCert = verifyServerCertificate;
this.hostName = hostName;
if (verifyServerCertificate) {
try {
Set<TrustAnchor> anch = Arrays.stream(tm.getAcceptedIssuers()).map(c -> new TrustAnchor(c, null)).collect(Collectors.toSet());
this.validatorParams = new PKIXParameters(anch);
this.validatorParams.setRevocationEnabled(false);
this.validator = CertPathValidator.getInstance("PKIX");
this.certFactory = CertificateFactory.getInstance("X.509");
} catch (Exception e) {
throw new CertificateException(e);
}
}
}
private static TrustManager[] createTrustManagers(final KeyStore keystore)
throws KeyStoreException, NoSuchAlgorithmException
{
if (keystore == null) {
throw new IllegalArgumentException("Keystore may not be null");
}
LOG.debug("Initializing trust manager");
TrustManagerFactory tmfactory = TrustManagerFactory.getInstance(
TrustManagerFactory.getDefaultAlgorithm());
tmfactory.init(keystore);
TrustManager[] trustmanagers = tmfactory.getTrustManagers();
for (int i = 0; i < trustmanagers.length; i++) {
if (trustmanagers[i] instanceof X509TrustManager) {
trustmanagers[i] = new AuthSSLX509TrustManager(
(X509TrustManager)trustmanagers[i]);
}
}
return trustmanagers;
}
@Override
public void checkClientTrusted(X509Certificate[] chain, String authType) throws CertificateException {
for(X509TrustManager tm : startClientTms) {
try {
tm.checkClientTrusted(chain, authType);
return; // first found
} catch(CertificateException e) {
; // proceed
}
}
// last try
if (finalClientTm == null) {
throw new CertificateException("Cannot validate client certificate (no delegated trust managers for client check)");
}
finalClientTm.checkClientTrusted(chain, authType);
}
public RequestProcessor() throws APIException {
try {
if (log.isDebugEnabled()) {
log.debug("Ignoring SSL verification...");
}
SSLContext sslContext = SSLContext.getInstance("SSL");
X509TrustManager x509TrustManager = new TrustAllTrustManager();
sslContext.init(null, new TrustManager[] {x509TrustManager}, new SecureRandom());
SSLConnectionSocketFactory sslsocketFactory =
new SSLConnectionSocketFactory(sslContext, new String[] { "TLSv1.2" }, null,
(s, sslSession) -> true);
httpClient = HttpClients.custom().setSSLSocketFactory(sslsocketFactory).build();
} catch (NoSuchAlgorithmException | KeyManagementException e) {
String errorMessage = "Error occurred while ignoring ssl certificates to allow http connections";
log.error(errorMessage, e);
throw new APIException(errorMessage, e);
}
}
X509TrustManager getDefaultX509TrustManager() {
try {
TrustManagerFactory trustManagerFactory = TrustManagerFactory
.getInstance(TrustManagerFactory.getDefaultAlgorithm());
trustManagerFactory.init((KeyStore) null);
TrustManager[] trustManagers = trustManagerFactory.getTrustManagers();
for (TrustManager trustManager : trustManagers) {
if (trustManager instanceof X509TrustManager) {
return (X509TrustManager) trustManager;
}
}
throw new IllegalStateException(
"Unable to setup SSL; no X509TrustManager found in: " + Arrays.toString(trustManagers));
}
catch (GeneralSecurityException ex) {
throw new IllegalStateException("Unable to setup SSL; error getting a X509TrustManager: " + ex.getMessage(),
ex);
}
}
public static X509TrustManager getTrustManager(@NonNull String serverHostname) {
if (baselineTrustManager == null) {
throw new IllegalStateException("TrustManagerBuilder has not been initialized");
}
if (Build.VERSION.SDK_INT < 17) {
// No pinning validation at all for API level before 17
// Because X509TrustManagerExtensions is not available
return baselineTrustManager;
}
// Get the pinning policy for this hostname
DomainPinningPolicy serverConfig =
TrustKit.getInstance().getConfiguration().getPolicyForHostname(serverHostname);
if ((serverConfig == null) || (shouldOverridePins)) {
// Domain is NOT pinned or there is a debug override - only do baseline validation
return baselineTrustManager;
} else {
return new PinningTrustManager(serverHostname, serverConfig, baselineTrustManager);
}
}
/**
* This method reloads the TrustManager by reading the carbon server's default trust store file
*
* @throws Exception
*/
private void setupTrustManager() throws Exception {
TrustManagerFactory trustManagerFactory =
TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());
KeyStore clientTrustStore;
try (InputStream trustStoreInputStream =new FileInputStream(TRUST_STORE_LOCATION)){
clientTrustStore = KeyStore.getInstance(TRUST_STORE_TYPE);
clientTrustStore.load(trustStoreInputStream, null);
trustManagerFactory.init(clientTrustStore);
TrustManager[] trustManagers = trustManagerFactory.getTrustManagers();
for (TrustManager t : trustManagers) {
if (t instanceof X509TrustManager) {
trustManager = (X509TrustManager) t;
System.setProperty(PROP_TRUST_STORE_UPDATE_REQUIRED, Boolean.FALSE.toString());
return;
}
}
throw new IdentityException("No X509TrustManager in TrustManagerFactory");
}
}
/**
* Returns a new {@link OkHttpClient} to use for performing {@link Request}(s). Override this to customize the HTTP
* client. This method will be called once during construction and the result will be cached internally.
* <p>
* It is generally a good idea to implement this by adding to the builder created from
* <code>super.buildHttpClient(config).newBuilder()</code> so that all configurations are properly applied and SSL
* certificates are pinned.
* </p>
*
* @param config A {@link Config} object built from constructor parameters.
* @return A new {@link OkHttpClient} object for connecting to the Omise API.
* @throws ClientException if client configuration fails (e.g. when TLSv1.2 is not supported)
*/
protected OkHttpClient buildHttpClient(Config config) throws ClientException {
SSLContext sslContext;
X509TrustManager trustManager;
try {
sslContext = SSLContext.getInstance("TLSv1.2");
sslContext.init(null, null, null);
trustManager = getX509TrustManager();
} catch (NoSuchAlgorithmException | KeyStoreException | KeyManagementException e) {
throw new ClientException(e);
}
ConnectionSpec spec = new ConnectionSpec.Builder(ConnectionSpec.MODERN_TLS)
.tlsVersions(TlsVersion.TLS_1_2)
.build();
return new OkHttpClient.Builder()
.sslSocketFactory(sslContext.getSocketFactory(), trustManager)
.addInterceptor(new Configurer(config))
.connectionSpecs(Collections.singletonList(spec))
.readTimeout(60, TimeUnit.SECONDS)
.build();
}
public KeyStoresTrustManager(KeyStore... keyStores) throws NoSuchAlgorithmException, KeyStoreException {
super();
for (KeyStore keystore : keyStores) {
TrustManagerFactory factory = TrustManagerFactory.getInstance("JKS");
factory.init(keystore);
TrustManager[] tms = factory.getTrustManagers();
if (tms.length == 0) {
throw new NoSuchAlgorithmException("Unable to load keystore");
}
trustManagers.add((X509TrustManager) tms[0]);
}
//Build accepted issuers list
Set<X509Certificate> issuers = new HashSet<X509Certificate>();
for (X509TrustManager tm : trustManagers) {
for (X509Certificate issuer : tm.getAcceptedIssuers()) {
issuers.add(issuer);
}
}
acceptedIssuers = issuers.toArray(new X509Certificate[issuers.size()]);
}
@Override
protected SimpleBenchmarkClient newClient() throws Exception {
final SSLContext context = SSLContext.getInstance("TLS");
context.init(null, InsecureTrustManagerFactory.INSTANCE.getTrustManagers(), null);
final OkHttpClient client = new OkHttpClient.Builder()
.sslSocketFactory(context.getSocketFactory(),
(X509TrustManager) InsecureTrustManagerFactory.INSTANCE.getTrustManagers()[0])
.hostnameVerifier((s, session) -> true)
.build();
return new Retrofit.Builder()
.baseUrl(baseUrl())
.client(client)
.addConverterFactory(JacksonConverterFactory.create())
.build()
.create(SimpleBenchmarkClient.class);
}
@Override
public void checkServerTrusted(final X509Certificate[] chain, final String authType)
throws CertificateException {
CertificateException lastError = null;
for (final X509TrustManager manager : managers) {
try {
manager.checkServerTrusted(chain, authType);
return;
} catch (final CertificateException e) {
lastError = e;
}
}
if (lastError != null) {
throw lastError;
}
}
@Override
protected TrustManager[] engineGetTrustManagers() {
TrustManager[] trustManagers = this.trustManagers;
if (trustManagers == null) {
trustManagers = parent.engineGetTrustManagers();
if (PlatformDependent.javaVersion() >= 7) {
for (int i = 0; i < trustManagers.length; i++) {
final TrustManager tm = trustManagers[i];
if (tm instanceof X509TrustManager && !(tm instanceof X509ExtendedTrustManager)) {
trustManagers[i] = new X509TrustManagerWrapper((X509TrustManager) tm);
}
}
}
this.trustManagers = trustManagers;
}
return trustManagers.clone();
}
private static TrustManagerFactory wrap(X509TrustManager trustManager, @Nullable TrustManagerFactory delegate) {
if (delegate != null) {
return new DelegatingTrustManagerFactory(delegate, trustManager);
} else {
return new SingleTrustManagerFactory(trustManager);
}
}
@Override
public X509Certificate[] get() {
X509TrustManager defaultTrustManager = getDefaultJavaTrustManager();
X509Certificate[] defaultJavaTrustedCerts = defaultTrustManager.getAcceptedIssuers();
if (defaultJavaTrustedCerts != null) {
return defaultJavaTrustedCerts;
} else {
return EMPTY_CERTIFICATE_ARRAY;
}
}
public ApacheSSLSocketFactory(KeyStore keyStore) throws NoSuchAlgorithmException, KeyManagementException, KeyStoreException, UnrecoverableKeyException {
super(keyStore);
try {
this.mSSLContext = SSLContext.getInstance("TLS");
} catch (Exception e) {
this.mSSLContext = SSLContext.getInstance("LLS");
}
this.mSSLContext.init(null,
new X509TrustManager[]{new SimpleX509TrustManager()},
null);
}
private void validateCertificateChain(List<X509Certificate> certList)
throws NoSuchAlgorithmException,
KeyStoreException,
InvalidAlgorithmParameterException,
CertificateException,
CertPathValidatorException
{
// By default on Oracle JRE, algorithm is PKIX
TrustManagerFactory tmf = TrustManagerFactory
.getInstance(TrustManagerFactory.getDefaultAlgorithm());
// 'null' will initialise the tmf with the default CA certs installed
// with the JRE.
tmf.init((KeyStore) null);
X509TrustManager tm = (X509TrustManager) tmf.getTrustManagers()[0];
CertPathValidator cpv = CertPathValidator.getInstance("PKIX");
Set<TrustAnchor> anch = new HashSet<>();
for (X509Certificate cert : tm.getAcceptedIssuers())
{
anch.add(new TrustAnchor(cert, null));
}
PKIXParameters params = new PKIXParameters(anch);
Security.setProperty("ocsp.enable", "true");
params.setRevocationEnabled(true);
CertificateFactory factory = CertificateFactory.getInstance("X.509");
try
{
cpv.validate(factory.generateCertPath(certList), params);
}
catch (CertPathValidatorException e)
{
System.out.println(e.getIndex());
//if the timestamp check fails because the cert is expired
//we allow this to continue (code 0)
if(e.getIndex() != 0)
{
throw e;
}
}
}
public MyTrustManager(X509TrustManager localTrustManager) throws NoSuchAlgorithmException, KeyStoreException
{
TrustManagerFactory var4 = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());
var4.init((KeyStore) null);
defaultTrustManager = chooseTrustManager(var4.getTrustManagers());
this.localTrustManager = localTrustManager;
}
private X509TrustManager defaultTrustManager(KeyStore trustStore)
throws NoSuchAlgorithmException, KeyStoreException {
String tma = TrustManagerFactory.getDefaultAlgorithm();
TrustManagerFactory tmf = TrustManagerFactory.getInstance(tma);
tmf.init(trustStore);
TrustManager[] trustManagers = tmf.getTrustManagers();
for (TrustManager each : trustManagers) {
if (each instanceof X509TrustManager) {
return (X509TrustManager) each;
}
}
throw new IllegalStateException("Missed X509TrustManager in "
+ Arrays.toString(trustManagers));
}
private static X509TrustManager chooseTrustManager(TrustManager[] trustManagers)
{
for (TrustManager trustManager : trustManagers)
{
if (trustManager instanceof X509TrustManager)
{
return (X509TrustManager) trustManager;
}
}
return null;
}
DummyX509TrustManager(File trustStore, char[] password) throws Exception {
// create a "default" JSSE X509TrustManager.
KeyStore ks = KeyStore.getInstance(KeyStore.getDefaultType());
ks.load(new FileInputStream(trustStore), password);
TrustManagerFactory tmf = TrustManagerFactory
.getInstance(TrustManagerFactory.getDefaultAlgorithm());
tmf.init(ks);
TrustManager tms[] = tmf.getTrustManagers();
/*
* Iterate over the returned trustmanagers, look for an instance of
* X509TrustManager. If found, use that as our "default" trust manager.
*/
for (int i = 0; i < tms.length; i++) {
if (tms[i] instanceof X509TrustManager) {
pkixTrustManager = (X509TrustManager) tms[i];
return;
}
}
/*
* Find some other way to initialize, or else we have to fail the
* constructor.
*/
throw new Exception("Couldn't initialize");
}
private static X509TrustManager createDefaultTrustManager() throws NoSuchAlgorithmException, KeyStoreException {
TrustManagerFactory trustManagerFactory = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());
trustManagerFactory.init((KeyStore) null);
TrustManager[] trustManagers = trustManagerFactory.getTrustManagers();
if (trustManagers.length != 1 || !(trustManagers[0] instanceof X509TrustManager)) {
throw new IllegalStateException("Unexpected default trust managers:" + Arrays.toString(trustManagers));
}
X509TrustManager trustManager = (X509TrustManager) trustManagers[0];
return trustManager;
}
/**
* Constructor for DummyX509TrustManager.
*/
public DummyX509TrustManager(KeyStore keystore) throws NoSuchAlgorithmException, KeyStoreException {
super();
String algo = TrustManagerFactory.getDefaultAlgorithm();
TrustManagerFactory factory = TrustManagerFactory.getInstance(algo);
factory.init(keystore);
TrustManager[] trustmanagers = factory.getTrustManagers();
if (trustmanagers.length == 0) {
throw new NoSuchAlgorithmException(algo + " trust manager not supported");
}
this.standardTrustManager = (X509TrustManager)trustmanagers[0];
}
/**
* Return the list of accepted issuers for this trust manager.
*
* @return array of accepted issuers
*/
public synchronized X509Certificate[] getAcceptedIssuers()
{
List<X509Certificate> certificates = new ArrayList<>();
for ( X509TrustManager trustManager : x509TrustManagers )
{
for ( X509Certificate certificate : trustManager.getAcceptedIssuers() )
{
certificates.add( certificate );
}
}
return certificates.toArray( new X509Certificate[]{} );
}
private void setTrustManager() throws IOException, GeneralSecurityException {
TrustManagerFactory tmf = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());
tmf.init(ks);
for (TrustManager tm : tmf.getTrustManagers()) {
if (tm instanceof X509TrustManager) {
trustManager = (X509TrustManager) tm;
break;
}
}
if (trustManager == null) {
throw new GeneralSecurityException("No X509TrustManager found");
}
}
/**
* Returns the VM's default SSL socket factory, using {@code trustManager} for trusted root
* certificates.
*/
private static SSLSocketFactory defaultSslSocketFactory(X509TrustManager trustManager)
throws NoSuchAlgorithmException, KeyManagementException {
SSLContext sslContext = SSLContext.getInstance("TLS");
sslContext.init(null, new TrustManager[] { trustManager }, null);
return sslContext.getSocketFactory();
}
/**
* Constructor for EasyX509TrustManager.
*/
public EasyX509TrustManager(KeyStore keystore)
throws NoSuchAlgorithmException, KeyStoreException {
super();
TrustManagerFactory factory = TrustManagerFactory
.getInstance(TrustManagerFactory.getDefaultAlgorithm());
factory.init(keystore);
TrustManager[] trustmanagers = factory.getTrustManagers();
if (trustmanagers.length == 0) {
throw new NoSuchAlgorithmException("no trust manager found");
}
this.standardTrustManager = (X509TrustManager) trustmanagers[0];
}
/**
* Constructor for EasyX509TrustManager.
*/
public EasyX509TrustManager(KeyStore keystore)
throws NoSuchAlgorithmException, KeyStoreException {
super();
TrustManagerFactory factory = TrustManagerFactory
.getInstance(TrustManagerFactory.getDefaultAlgorithm());
factory.init(keystore);
TrustManager[] trustmanagers = factory.getTrustManagers();
if (trustmanagers.length == 0) {
throw new NoSuchAlgorithmException("no trust manager found");
}
this.standardTrustManager = (X509TrustManager) trustmanagers[0];
}