Avatar billede krukken Mester
12. april 2005 - 15:39 Der er 1 kommentar og
1 løsning

Importer certifikat.cer i KeyStore og forbinde til webservice

Hej,

Jeg har store problemer at med at forbinde til webservicen cvr.dk. Jeg har følgende kode:
webservice.java
*****************************
import dk.oio.rep.cvr_dk.xml.schemas.LegalUnit._2002._07._03.LegalUnit;

import javax.xml.rpc.ServiceException;
import javax.net.ssl.*;

import cvrwebservice.CVRPortType;
import cvrwebservice.CVRBindingStub;
import cvrwebservice.CVRWebServiceLocator;
import org.apache.axis.AxisFault;


import java.rmi.RemoteException;
import java.security.cert.X509Certificate;
import java.security.cert.CertificateException;
import java.security.NoSuchAlgorithmException;
import java.io.IOException;


public class Webservice
{

    public static void main(String[] args)
    {

        CertificateReader reader = new CertificateReader("onlinecvrdk.crt");
        TrustManager[] trustAllCerts = new TrustManager[]
        {
            new X509TrustManager()
            {
                public java.security.cert.X509Certificate[] getAcceptedIssuers()
                {
                    X509Certificate[] temp = new X509Certificate[0];
                    try
                    {
                        temp[0] = CertificateReader.getCertificate("onlinecvrdk.crt");
                    }
                    catch (CertificateException e)
                    {
                        e.printStackTrace();  //To change body of catch statement use File | Settings | File Templates.
                    } catch (IOException e)
                    {
                        e.printStackTrace();  //To change body of catch statement use File | Settings | File Templates.
                    }
                    return temp;
                }

                public void checkClientTrusted(java.security.cert.X509Certificate[] certs, String authType)
                {

                }
                public void checkServerTrusted(java.security.cert.X509Certificate[] certs, String authType)
                {

                }
            }
        };

        try
        {
            SSLContext sc = SSLContext.getInstance("SSL");
            sc.init(null, trustAllCerts, new java.security.SecureRandom());
            HttpsURLConnection.setDefaultSSLSocketFactory(sc.getSocketFactory());
        }
        catch (Exception e)
        {
            e.printStackTrace();
        }
        HostnameVerifier hv = new HostnameVerifier()
        {
            public boolean verify(String urlHostName, SSLSession session)
            {
                return true;
            }
        };
        HttpsURLConnection.setDefaultHostnameVerifier(hv);



        String opslag = "27103235";
        String user =  "bruger";
        String kode = "hemmelig";
        int level = 2;
        LegalUnit unit = null;

        CVRWebServiceLocator cvr = new cvrwebservice.CVRWebServiceLocator();
        CVRBindingStub stub = null;

        try
        {
            stub = new CVRBindingStub(cvr);
            stub.setPassword(kode);
            stub.setUsername(user);
        }
        catch (AxisFault axisFault)
        {
            axisFault.printStackTrace();
            System.out.println("AxisFault");
        }
        CVRPortType port = null;

        try
        {
            port = cvr.getCVRPort();
        }
        catch (ServiceException e)
        {
            e.printStackTrace();
            System.out.println("ServiceException");
        }
        try
        {
            unit = new LegalUnit();
            unit = port.getLegalUnit(user,kode,opslag,level);
        }
        catch (RemoteException e)
        {
            e.printStackTrace();
            System.out.println("RemoteException");
        }
        System.out.println(unit.getOfficialAddress().getGeneralAddress().getRoadName());
    }
}
************************************


Her er en klasse som læser certifikaterne - ligger dem i Keystore:
CertificateReader.java
***************************************
import java.io.InputStream;
import java.io.IOException;
import java.io.FileNotFoundException;
import java.util.Date;
import java.security.KeyStore;
import java.security.PublicKey;
import java.security.KeyStoreException;
import java.security.NoSuchAlgorithmException;
import java.security.cert.CertificateException;
import java.security.cert.CertificateFactory;
import java.security.cert.X509Certificate;
import java.security.cert.CertificateExpiredException;
import java.security.cert.CertificateNotYetValidException;

public class CertificateReader
{
    private PublicKey publicKey;

    public CertificateReader(String file)
    {
        try
        {
            // Create KeyStore to hold certificate from CVR
            KeyStore keyStore = createKeyStore();
            // Create X509Certificate object from downloaded file with certificate
            X509Certificate x509certificate = getCertificate(file);
            // Check validity of certificate
            checkCertificateValidity(x509certificate);
            // Put X509Certificate in keyStore
            keyStore.setCertificateEntry("MyCertificate", x509certificate);
            // Get public key from MyCertificate via keyStore
            PublicKey publicKey = keyStore.getCertificate("MyCertificate").getPublicKey();
            // Output publicKey to Console
            System.out.println(publicKey.toString());
        }
        catch (FileNotFoundException fileNotFoundException)
        {
            fileNotFoundException.printStackTrace();
        }
        catch (IOException ioException)
        {
            ioException.printStackTrace();
        }
        catch (CertificateNotYetValidException certificateNotYetValidException)
        {
            certificateNotYetValidException.printStackTrace();
        }
        catch (CertificateExpiredException certificateExpiredException)
        {
            certificateExpiredException.printStackTrace();
        }
        catch (CertificateException certificateException)
        {
            certificateException.printStackTrace();
        }
        catch (KeyStoreException keyStoreException)
        {
            keyStoreException.printStackTrace();
        }
        catch (NoSuchAlgorithmException noSuchAlgorithmException)
        {
            noSuchAlgorithmException.printStackTrace();
        }
    }

    public static void checkCertificateValidity(X509Certificate x509certificate) throws CertificateExpiredException, CertificateNotYetValidException
    {
        Date date = new Date();
        x509certificate.checkValidity(date);
    }

    public static X509Certificate getCertificate(String arstring) throws CertificateException, FileNotFoundException, IOException
    {
        CertificateFactory certificatefactory = CertificateFactory.getInstance("X.509");
        InputStream inputstream = null;
        // Read certificate from file
        inputstream = new java.io.FileInputStream(arstring);
        inputstream = new java.io.BufferedInputStream(inputstream);
        // create X509Certificate object
        X509Certificate x509certificate = (X509Certificate) certificatefactory.generateCertificate(inputstream);
        inputstream.close();
        return x509certificate;
    }

    public static KeyStore createKeyStore() throws KeyStoreException, CertificateException, NoSuchAlgorithmException, IOException
    {
        KeyStore keyStore = null;
        // Get instance of KeyStore of type JKS - JavaKeyStore
        keyStore = KeyStore.getInstance("JKS");
        // Initialize keyStore
        keyStore.load(null, null);
        return keyStore;
    }

    public PublicKey getPublicKey()
    {
        return publicKey;
    }
}
*************************************
Avatar billede krukken Mester
12. april 2005 - 15:40 #1
og jeg får følgende fejl når jeg kalder unit = port.getLegalUnituser,kode,opslag,level):
AxisFault
faultCode: {http://schemas.xmlsoap.org/soap/envelope/}Server.userException
faultSubcode:
faultString: javax.net.ssl.SSLHandshakeException: sun.security.validator.ValidatorException: PKIX path building failed: sun.security.provider.certpath.SunCertPathBuilderException: unable to find valid certification path to requested target
faultActor:
faultNode:
faultDetail:
    {http://xml.apache.org/axis/}stackTrace:javax.net.ssl.SSLHandshakeException: sun.security.validator.ValidatorException: PKIX path building failed: sun.security.provider.certpath.SunCertPathBuilderException: unable to find valid certification path to requested target
    at com.sun.net.ssl.internal.ssl.Alerts.getSSLException(Alerts.java:150)
    at com.sun.net.ssl.internal.ssl.SSLSocketImpl.fatal(SSLSocketImpl.java:1476)
    at com.sun.net.ssl.internal.ssl.Handshaker.fatalSE(Handshaker.java:174)
    at com.sun.net.ssl.internal.ssl.Handshaker.fatalSE(Handshaker.java:168)
    at com.sun.net.ssl.internal.ssl.ClientHandshaker.serverCertificate(ClientHandshaker.java:846)
    at com.sun.net.ssl.internal.ssl.ClientHandshaker.processMessage(ClientHandshaker.java:106)
    at com.sun.net.ssl.internal.ssl.Handshaker.processLoop(Handshaker.java:495)
    at com.sun.net.ssl.internal.ssl.Handshaker.process_record(Handshaker.java:433)
    at com.sun.net.ssl.internal.ssl.SSLSocketImpl.readRecord(SSLSocketImpl.java:815)
    at com.sun.net.ssl.internal.ssl.SSLSocketImpl.performInitialHandshake(SSLSocketImpl.java:1025)
    at com.sun.net.ssl.internal.ssl.SSLSocketImpl.startHandshake(SSLSocketImpl.java:1038)
    at org.apache.axis.components.net.JSSESocketFactory.create(JSSESocketFactory.java:186)
    at org.apache.axis.transport.http.HTTPSender.getSocket(HTTPSender.java:131)
    at org.apache.axis.transport.http.HTTPSender.writeToSocket(HTTPSender.java:370)
    at org.apache.axis.transport.http.HTTPSender.invoke(HTTPSender.java:88)
    at org.apache.axis.strategies.InvocationStrategy.visit(InvocationStrategy.java:32)
    at org.apache.axis.SimpleChain.doVisiting(SimpleChain.java:118)
    at org.apache.axis.SimpleChain.invoke(SimpleChain.java:83)
    at org.apache.axis.client.AxisClient.invoke(AxisClient.java:147)
    at org.apache.axis.client.Call.invokeEngine(Call.java:2719)
    at org.apache.axis.client.Call.invoke(Call.java:2702)
    at org.apache.axis.client.Call.invoke(Call.java:2378)
    at org.apache.axis.client.Call.invoke(Call.java:2301)
    at org.apache.axis.client.Call.invoke(Call.java:1758)
    at cvrwebservice.CVRBindingStub.getLegalUnit(Unknown Source)
    at Webservice.main(Webservice.java:113)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25)
    at java.lang.reflect.Method.invoke(Method.java:585)
    at com.intellij.rt.execution.application.AppMain.main(AppMain.java:78)
Caused by: sun.security.validator.ValidatorException: PKIX path building failed: sun.security.provider.certpath.SunCertPathBuilderException: unable to find valid certification path to requested target
    at sun.security.validator.PKIXValidator.doBuild(PKIXValidator.java:221)
    at sun.security.validator.PKIXValidator.engineValidate(PKIXValidator.java:145)
    at sun.security.validator.Validator.validate(Validator.java:203)
    at com.sun.net.ssl.internal.ssl.X509TrustManagerImpl.checkServerTrusted(X509TrustManagerImpl.java:172)
    at com.sun.net.ssl.internal.ssl.JsseX509TrustManager.checkServerTrusted(SSLContextImpl.java:320)
    at com.sun.net.ssl.internal.ssl.ClientHandshaker.serverCertificate(ClientHandshaker.java:839)
    ... 26 more
Caused by: sun.security.provider.certpath.SunCertPathBuilderException: unable to find valid certification path to requested target
    at sun.security.provider.certpath.SunCertPathBuilder.engineBuild(SunCertPathBuilder.java:236)
    at java.security.cert.CertPathBuilder.build(CertPathBuilder.java:194)
    at sun.security.validator.PKIXValidator.doBuild(PKIXValidator.java:216)
    ... 31 more

    {http://xml.apache.org/axis/}hostname:brianstation

javax.net.ssl.SSLHandshakeException: sun.security.validator.ValidatorException: PKIX path building failed: sun.security.provider.certpath.SunCertPathBuilderException: unable to find valid certification path to requested target
    at org.apache.axis.AxisFault.makeFault(AxisFault.java:101)
    at org.apache.axis.transport.http.HTTPSender.invoke(HTTPSender.java:97)
    at org.apache.axis.strategies.InvocationStrategy.visit(InvocationStrategy.java:32)
    at org.apache.axis.SimpleChain.doVisiting(SimpleChain.java:118)
    at org.apache.axis.SimpleChain.invoke(SimpleChain.java:83)
    at org.apache.axis.client.AxisClient.invoke(AxisClient.java:147)
    at org.apache.axis.client.Call.invokeEngine(Call.java:2719)
    at org.apache.axis.client.Call.invoke(Call.java:2702)
    at org.apache.axis.client.Call.invoke(Call.java:2378)
    at org.apache.axis.client.Call.invoke(Call.java:2301)
    at org.apache.axis.client.Call.invoke(Call.java:1758)
    at cvrwebservice.CVRBindingStub.getLegalUnit(Unknown Source)
    at Webservice.main(Webservice.java:113)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25)
    at java.lang.reflect.Method.invoke(Method.java:585)
    at com.intellij.rt.execution.application.AppMain.main(AppMain.java:78)
Caused by: javax.net.ssl.SSLHandshakeException: sun.security.validator.ValidatorException: PKIX path building failed: sun.security.provider.certpath.SunCertPathBuilderException: unable to find valid certification path to requested target
    at com.sun.net.ssl.internal.ssl.Alerts.getSSLException(Alerts.java:150)
    at com.sun.net.ssl.internal.ssl.SSLSocketImpl.fatal(SSLSocketImpl.java:1476)
    at com.sun.net.ssl.internal.ssl.Handshaker.fatalSE(Handshaker.java:174)
    at com.sun.net.ssl.internal.ssl.Handshaker.fatalSE(Handshaker.java:168)
    at com.sun.net.ssl.internal.ssl.ClientHandshaker.serverCertificate(ClientHandshaker.java:846)
    at com.sun.net.ssl.internal.ssl.ClientHandshaker.processMessage(ClientHandshaker.java:106)
    at com.sun.net.ssl.internal.ssl.Handshaker.processLoop(Handshaker.java:495)
    at com.sun.net.ssl.internal.ssl.Handshaker.process_record(Handshaker.java:433)
    at com.sun.net.ssl.internal.ssl.SSLSocketImpl.readRecord(SSLSocketImpl.java:815)
    at com.sun.net.ssl.internal.ssl.SSLSocketImpl.performInitialHandshake(SSLSocketImpl.java:1025)
    at com.sun.net.ssl.internal.ssl.SSLSocketImpl.startHandshake(SSLSocketImpl.java:1038)
    at org.apache.axis.components.net.JSSESocketFactory.create(JSSESocketFactory.java:186)
    at org.apache.axis.transport.http.HTTPSender.getSocket(HTTPSender.java:131)
    at org.apache.axis.transport.http.HTTPSender.writeToSocket(HTTPSender.java:370)
    at org.apache.axis.transport.http.HTTPSender.invoke(HTTPSender.java:88)
    ... 16 more
Caused by: sun.security.validator.ValidatorException: PKIX path building failed: sun.security.provider.certpath.SunCertPathBuilderException: unable to find valid certification path to requested target
    at sun.security.validator.PKIXValidator.doBuild(PKIXValidator.java:221)
    at sun.security.validator.PKIXValidator.engineValidate(PKIXValidator.java:145)
    at sun.security.validator.Validator.validate(Validator.java:203)
    at com.sun.net.ssl.internal.ssl.X509TrustManagerImpl.checkServerTrusted(X509TrustManagerImpl.java:172)
    at com.sun.net.ssl.internal.ssl.JsseX509TrustManager.checkServerTrusted(SSLContextImpl.java:320)
    at com.sun.net.ssl.internal.ssl.ClientHandshaker.serverCertificate(ClientHandshaker.java:839)
    ... 26 more
Caused by: sun.security.provider.certpath.SunCertPathBuilderException: unable to find valid certification path to requested target
    at sun.security.provider.certpath.SunCertPathBuilder.engineBuild(SunCertPathBuilder.java:236)
    at java.security.cert.CertPathBuilder.build(CertPathBuilder.java:194)
    at sun.security.validator.PKIXValidator.doBuild(PKIXValidator.java:216)
    ... 31 more
Exception in thread "main" java.lang.NullPointerException
    at Webservice.main(Webservice.java:120)
RemoteException
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25)
    at java.lang.reflect.Method.invoke(Method.java:585)
    at com.intellij.rt.execution.application.AppMain.main(AppMain.java:78)
Avatar billede krukken Mester
19. april 2005 - 20:59 #2
Intet svar
Avatar billede Ny bruger Nybegynder

Din løsning...

Tilladte BB-code-tags: [b]fed[/b] [i]kursiv[/i] [u]understreget[/u] Web- og emailadresser omdannes automatisk til links. Der sættes "nofollow" på alle links.

Loading billede Opret Preview
Kategori
Kurser inden for grundlæggende programmering

Log ind eller opret profil

Hov!

For at kunne deltage på Computerworld Eksperten skal du være logget ind.

Det er heldigvis nemt at oprette en bruger: Det tager to minutter og du kan vælge at bruge enten e-mail, Facebook eller Google som login.

Du kan også logge ind via nedenstående tjenester