Skip to content

Instantly share code, notes, and snippets.

@swallez
Created March 14, 2023 22:05
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save swallez/0a51b260acd027a4561f72e782bce252 to your computer and use it in GitHub Desktop.
Save swallez/0a51b260acd027a4561f72e782bce252 to your computer and use it in GitHub Desktop.
A Java SSLContext that will accept any certificate (dangerous for production, useful for tests with a self-signed certificate)
import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLSocketFactory;
import javax.net.ssl.X509TrustManager;
import java.security.cert.X509Certificate;
public class SSLUtils {
private static SSLContext yesCtx = null;
/**
* Returns an SSLContext that will accept any server certificate.
* Use with great care and in limited situations, as it allows MITM attacks.
*/
public static SSLContext yesSSLContext() {
if (yesCtx == null) {
X509TrustManager yesTm = new X509TrustManager() {
@Override
public void checkClientTrusted(X509Certificate[] certs, String authType) {
// Accept anything
}
@Override
public void checkServerTrusted(X509Certificate[] certs, String authType) {
// Accept anything
}
@Override
public X509Certificate[] getAcceptedIssuers() {
return new X509Certificate[0];
}
};
try {
SSLContext ctx = SSLContext.getInstance("SSL");
ctx.init(null, new X509TrustManager[] { yesTm }, null);
yesCtx = ctx;
} catch (Exception e) {
// An exception here means SSL is not supported, which is unlikely
throw new RuntimeException(e);
}
}
return yesCtx;
}
public static SSLSocketFactory yesSSLSocketFactory() {
return yesSSLContext().getSocketFactory();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment