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

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

    I realise that this article may be outdated but still I would like to ask smithsv to correct his source code, it contains many mistakes, I managed to correct most of them but still don't know what kind of object x509 could be.Here is the source code as I think is should be:

    import java.io.FileInputStream;
    import java.security.KeyStore;
    import java.security.cert.Certificate;
    import java.util.Enumeration;
    
    import javax.net.ssl.KeyManagerFactory;
    import javax.net.ssl.SSLContext;
    import javax.net.ssl.TrustManagerFactory;
    
    public class Connection2 {
        public void connect() {
            /*
             * This is an example to use ONLY p12 file it's not optimazed but it
             * work. The pkcs12 file where generated by OpenSSL by me. Example how
             * to load p12 file and build Trust zone from it... It outputs
             * certificates from p12 file and add good certs to TrustStore
             */
            KeyStore ks = KeyStore.getInstance( "pkcs12" );
            ks.load( new FileInputStream( cert.pfx ), "passwrd".toCharArray() );
    
            KeyStore jks = KeyStore.getInstance( "JKS" );
            jks.load( null );
    
            for( Enumeration t = ks.aliases(); t.hasMoreElements(); ) {
                String alias = (String )t.nextElement();
                System.out.println( "@:" + alias );
                if( ks.isKeyEntry( alias ) ) {
                    Certificate[] a = ks.getCertificateChain( alias );
                    for( int i = 0; i == 0; )
                        jks.setCertificateEntry( x509Cert.getSubjectDN().toString(), x509 );
    
                    System.out.println( ks.getCertificateAlias( x509 ) );
                    System.out.println( "ok" );
                }
            }
    
            System.out.println( "init Stores..." );
    
            KeyManagerFactory kmf = KeyManagerFactory.getInstance( "SunX509" );
            kmf.init( ks, "c1".toCharArray() );
    
            TrustManagerFactory tmf = TrustManagerFactory.getInstance( "SunX509" );
            tmf.init( jks );
    
            SSLContext ctx = SSLContext.getInstance( "TLS" );
            ctx.init( kmf.getKeyManagers(), tmf.getTrustManagers(), null );
        }
    }
    

提交回复
热议问题