Restore SSL X509TrustManager in Java -
i have following code conditionally (based on boolean
) disables ssl certificate checking.
however, if set boolean
false
, re-run code, ssl checking still seems disabled (when should re-enabled).
so, what's opposite logic of this, checking restored?
if (bignoressl) { trustmanager[] trustallcertificates = new trustmanager[] { new x509trustmanager() { @override public x509certificate[] getacceptedissuers() { return null; // not relevant.} @override public void checkclienttrusted(x509certificate[] certs, string authtype) { // nothing. allow them all. } @override public void checkservertrusted(x509certificate[] certs, string authtype){ // nothing. allow them all.} } }; hostnameverifier trustallhostnames = new hostnameverifier() { @override public boolean verify(string hostname, sslsession session) { return true; // allow them all. } }; try { system.setproperty("jsse.enablesniextension", "false"); sslcontext sc = sslcontext.getinstance("ssl"); sc.init(null, trustallcertificates, new securerandom()); httpsurlconnection.setdefaultsslsocketfactory(sc.getsocketfactory()); httpsurlconnection.setdefaulthostnameverifier(trustallhostnames); } catch (generalsecurityexception e) { throw new exceptionininitializererror(e); } } else { // code restore here (opposite of above?) }
one alternative first save defaults in variable, can restore them later:
// save defaults (do before setting defaults) hostnameverifier defaultverifier = httpsurlconnection.getdefaulthostnameverifier(); sslsocketfactory defaultfactory = httpsurlconnection.getdefaultsslsocketfactory(); if (bignoressl) { ... } else { // restore defaults httpsurlconnection.setdefaulthostnameverifier(defaultverifier); httpsurlconnection.setdefaultsslsocketfactory(defaultfactory); }
another alternative (a better one, imo) not set default connections, set each individual connection instead:
httpsurlconnection conn = // create connection if (bignoressl) { // set custom verifier , factory connection conn.sethostnameverifier(trustallhostnames); conn.setsslsocketfactory(sc.getsocketfactory()); } // no need restore (else), didn't change defaults
this changes verifier , factory specified connection, without affecting defaults (so there's no need restore).
Comments
Post a Comment