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

前端 未结 8 1354
野性不改
野性不改 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:26

    This example shows how you can layer SSL on top of an existing socket, obtaining the client cert from a PKCS#12 file. It is appropriate when you need to connect to an upstream server via a proxy, and you want to handle the full protocol by yourself.

    Essentially, however, once you have the SSL Context, you can apply it to an HttpsURLConnection, etc, etc.

    KeyStore ks = KeyStore.getInstance("PKCS12");
    InputStream is = ...;
    char[] ksp = storePassword.toCharArray();
    ks.load(is, ksp);
    KeyManagerFactory kmf = KeyManagerFactory.getInstance("SunX509");
    char[] kp = keyPassword.toCharArray();
    kmf.init(ks, kp);
    sslContext = SSLContext.getInstance("SSLv3");
    sslContext.init(kmf.getKeyManagers(), null, null);
    SSLSocketFactory factory = sslContext.getSocketFactory();
    SSLSocket sslsocket = (SSLSocket) factory.createSocket(socket, socket
        .getInetAddress().getHostName(), socket.getPort(), true);
    sslsocket.setUseClientMode(true);
    sslsocket.setSoTimeout(soTimeout);
    sslsocket.startHandshake();
    

提交回复
热议问题