How to connect to a secure website using SSL in Java with a pkcs12 file?

前端 未结 8 1362
野性不改
野性不改 2020-12-01 06:37

I have a pkcs12 file. I need to use this to connect to a webpage using https protocol. I came across some code where in order to connect to a secure web page i need to set t

8条回答
  •  囚心锁ツ
    2020-12-01 07:32

    URL url = new URL("https://test.domain:443");   
    String  keyStore = "server.p12"
    String   keyStorePassword = "changeit";    
    String  keyPassword = "changeit";    
    String   KeyStoreType= "PKCS12";    
    String   KeyManagerAlgorithm = "SunX509";    
    String   SSLVersion = "SSLv3";    
    public HttpURLConnection getHttpsURLConnection(URL url, String  keystore,
        String   keyStorePass,String  keyPassword, String  KeyStoreType
        ,String KeyManagerAlgorithm, String  SSLVersion)
        throws NoSuchAlgorithmException, KeyStoreException,
            CertificateException, FileNotFoundException, IOException,
            UnrecoverableKeyException, KeyManagementException {
        System.setProperty("javax.net.debug","ssl,handshake,record");
    
        SSLContext sslcontext = SSLContext.getInstance(SSLVersion);
        KeyManagerFactory kmf =  KeyManagerFactory.getInstance(KeyManagerAlgorithm);
        KeyStore ks = KeyStore.getInstance(KeyStoreType);
        ks.load(new FileInputStream(keystore), keyStorePass.toCharArray());
        kmf.init(ks, keyPassword.toCharArray());
    
         TrustManagerFactory tmf = TrustManagerFactory
                .getInstance(TrustManagerFactory.getDefaultAlgorithm());
        tmf.init(ks);
        TrustManager[] tm = tmf.getTrustManagers();
    
        sslcontext.init(kmf.getKeyManagers(), tm, null);
        SSLSocketFactory sslSocketFactory = sslcontext.getSocketFactory();
        HttpsURLConnection.setDefaultSSLSocketFactory(sslSocketFactory);
        HttpsURLConnection httpsURLConnection = ( HttpsURLConnection)uRL.openConnection();
    
        return httpsURLConnection;
    }
    

提交回复
热议问题