1

我将 keystore.jks 和 cacerts 文件复制到了 src/main/resources 下的 restapi 项目中。并面临以下异常。

但是当我尝试从 linux 路径中读取 keystore.jks 和 cacerts 文件时[而不是从资源目录中读取],它可以工作。

例外 :

Reading the Certificate file from resource dir...file:/home/raam/apache-tomcat-9.0.22/webapps/SampleRestApi/WEB-INF/classes/keystore.jks
java.security.cert.CertificateParsingException: java.io.IOException: DerInputStream.getLength(): lengthTag=53, too big.
        at sun.security.x509.X509CertInfo.<init>(X509CertInfo.java:169)
        at sun.security.x509.X509CertImpl.parse(X509CertImpl.java:1804)
        at sun.security.x509.X509CertImpl.<init>(X509CertImpl.java:195)
        at sun.security.provider.X509Factory.engineGenerateCertificate(X509Factory.java:102)
        at java.security.cert.CertificateFactory.generateCertificate(CertificateFactory.java:339)
        at sun.security.provider.JavaKeyStore.engineLoad(JavaKeyStore.java:716)
        at sun.security.provider.JavaKeyStore$JKS.engineLoad(JavaKeyStore.java:56)
        at sun.security.provider.KeyStoreDelegator.engineLoad(KeyStoreDelegator.java:224)
        at sun.security.provider.JavaKeyStore$DualFormatJKS.engineLoad(JavaKeyStore.java:70)
        at java.security.KeyStore.load(KeyStore.java:1445)
        at com.test.api.utils.HttpCilentUtil.getHttpsClient(HttpCilentUtil.java:94)
        at com.test.api.utils.HttpCilentUtil.auditLogPost(HttpCilentUtil.java:33)
        at com.test.api.BalanceServiceImpl.auditLog(BalanceServiceImpl.java:37)
        at com.test.api.BalanceServiceImpl.getBalance(BalanceServiceImpl.java:30)
        at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
        at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
        at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
        at java.lang.reflect.Method.invoke(Method.java:498)
        at com.sun.jersey.spi.container.JavaMethodInvokerFactory$1.invoke(JavaMethodInvokerFactory.java:60)
        at com.sun.jersey.server.impl.model.method.dispatch.AbstractResourceMethodDispatchProvider$ResponseOutInvoker._dispatch(AbstractResourceMethodDispatchProvider.java:205)
        at com.sun.jersey.server.impl.model.method.dispatch.ResourceJavaMethodDispatcher.dispatch(ResourceJavaMethodDispatcher.java:75)
        at com.sun.jersey.server.impl.uri.rules.HttpMethodRule.accept(HttpMethodRule.java:288)
        at com.sun.jersey.server.impl.uri.rules.RightHandPathRule.accept(RightHandPathRule.java:147)
        at com.sun.jersey.server.impl.uri.rules.ResourceClassRule.accept(ResourceClassRule.java:108)
        at com.sun.jersey.server.impl.uri.rules.RightHandPathRule.accept(RightHandPathRule.java:147)
        at com.sun.jersey.server.impl.uri.rules.RootResourceClassesRule.accept(RootResourceClassesRule.java:84)
        at com.sun.jersey.server.impl.application.WebApplicationImpl._handleRequest(WebApplicationImpl.java:1469)
        at com.sun.jersey.server.impl.application.WebApplicationImpl._handleRequest(WebApplicationImpl.java:1400)
        at com.sun.jersey.server.impl.application.WebApplicationImpl.handleRequest(WebApplicationImpl.java:1349)
        at com.sun.jersey.server.impl.application.WebApplicationImpl.handleRequest(WebApplicationImpl.java:1339)
        at com.sun.jersey.spi.container.servlet.WebComponent.service(WebComponent.java:416)
        at com.sun.jersey.spi.container.servlet.ServletContainer.service(ServletContainer.java:537)
        at com.sun.jersey.spi.container.servlet.ServletContainer.service(ServletContainer.java:699)
        at javax.servlet.http.HttpServlet.service(HttpServlet.java:741)
        at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:231)
        at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166)
        at org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:53)
        at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193)
        at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166)
        at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:202)
        at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:96)
        at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:490)
        at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:139)
        at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:92)
        at org.apache.catalina.valves.AbstractAccessLogValve.invoke(AbstractAccessLogValve.java:678)
        at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:74)
        at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:343)
        at org.apache.coyote.http11.Http11Processor.service(Http11Processor.java:408)
        at org.apache.coyote.AbstractProcessorLight.process(AbstractProcessorLight.java:66)
        at org.apache.coyote.AbstractProtocol$ConnectionHandler.process(AbstractProtocol.java:853)
        at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.doRun(NioEndpoint.java:1587)
        at org.apache.tomcat.util.net.SocketProcessorBase.run(SocketProcessorBase.java:49)
        at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142)
        at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617)
        at org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61)
        at java.lang.Thread.run(Thread.java:745)
Caused by: java.io.IOException: DerInputStream.getLength(): lengthTag=53, too big.
        at sun.security.util.DerInputStream.getLength(DerInputStream.java:599)
        at sun.security.util.DerValue.<init>(DerValue.java:252)
        at sun.security.util.DerInputStream.readVector(DerInputStream.java:424)
        at sun.security.util.DerInputStream.getSequence(DerInputStream.java:332)
        at sun.security.x509.X500Name.parseDER(X500Name.java:793)
        at sun.security.x509.X500Name.<init>(X500Name.java:306)
        at sun.security.x509.X509CertInfo.parse(X509CertInfo.java:649)
        at sun.security.x509.X509CertInfo.<init>(X509CertInfo.java:167)
        ... 55 more
29-Aug-2019 17:21:56.204 SEVERE [http-nio-8080-exec-1] com.sun.jersey.spi.container.ContainerResponse.mapMappableContainerException The RuntimeException could not be mapped to a response, re-throwing to the HTTP container
        java.lang.NullPointerException
                at com.test.api.utils.HttpCilentUtil.auditLogPost(HttpCilentUtil.java:77)
                at com.test.api.BalanceServiceImpl.auditLog(BalanceServiceImpl.java:37)
                at com.test.api.BalanceServiceImpl.getBalance(BalanceServiceImpl.java:30)
                at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
                at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
                at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
                at java.lang.reflect.Method.invoke(Method.java:498)
                at com.sun.jersey.spi.container.JavaMethodInvokerFactory$1.invoke(JavaMethodInvokerFactory.java:60)
                at com.sun.jersey.server.impl.model.method.dispatch.AbstractResourceMethodDispatchProvider$ResponseOutInvoker._dispatch(AbstractResourceMethodDispatchProvider.java:205)
                at com.sun.jersey.server.impl.model.method.dispatch.ResourceJavaMethodDispatcher.dispatch(ResourceJavaMethodDispatcher.java:75)
                at com.sun.jersey.server.impl.uri.rules.HttpMethodRule.accept(HttpMethodRule.java:288)
                at com.sun.jersey.server.impl.uri.rules.RightHandPathRule.accept(RightHandPathRule.java:147)
                at com.sun.jersey.server.impl.uri.rules.ResourceClassRule.accept(ResourceClassRule.java:108)
                at com.sun.jersey.server.impl.uri.rules.RightHandPathRule.accept(RightHandPathRule.java:147)
                at com.sun.jersey.server.impl.uri.rules.RootResourceClassesRule.accept(RootResourceClassesRule.java:84)
                at com.sun.jersey.server.impl.application.WebApplicationImpl._handleRequest(WebApplicationImpl.java:1469)
                at com.sun.jersey.server.impl.application.WebApplicationImpl._handleRequest(WebApplicationImpl.java:1400)
                at com.sun.jersey.server.impl.application.WebApplicationImpl.handleRequest(WebApplicationImpl.java:1349)
                at com.sun.jersey.server.impl.application.WebApplicationImpl.handleRequest(WebApplicationImpl.java:1339)
                at com.sun.jersey.spi.container.servlet.WebComponent.service(WebComponent.java:416)
                at com.sun.jersey.spi.container.servlet.ServletContainer.service(ServletContainer.java:537)
                at com.sun.jersey.spi.container.servlet.ServletContainer.service(ServletContainer.java:699)
                at javax.servlet.http.HttpServlet.service(HttpServlet.java:741)
                at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:231)
                at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166)
                at org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:53)
                at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193)
                at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166)
                at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:202)
                at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:96)
                at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:490)
                at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:139)
                at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:92)
                at org.apache.catalina.valves.AbstractAccessLogValve.invoke(AbstractAccessLogValve.java:678)
                at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:74)
                at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:343)
                at org.apache.coyote.http11.Http11Processor.service(Http11Processor.java:408)
                at org.apache.coyote.AbstractProcessorLight.process(AbstractProcessorLight.java:66)
                at org.apache.coyote.AbstractProtocol$ConnectionHandler.process(AbstractProtocol.java:853)
                at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.doRun(NioEndpoint.java:1587)
                at org.apache.tomcat.util.net.SocketProcessorBase.run(SocketProcessorBase.java:49)
                at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142)
                at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617)
                at org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61)
                at java.lang.Thread.run(Thread.java:745)

下面是我试图通过从资源目录中读取 jks 文件来运行的代码。

public class HttpCilentExample {

    public static void main(String[] args) throws Exception {
        HttpCilentExample client = new HttpCilentExample();
        client.post();
    }


    public void post() throws IOException {
        String url = "https://localhost:8080/listener";
        CloseableHttpClient client = null;
        try {
            client = getHttpsClient();
        } catch (KeyStoreException e) {
            e.printStackTrace();
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        } catch (CertificateException e) {
            e.printStackTrace();
        } catch (KeyManagementException e) {
            e.printStackTrace();
        } catch (UnrecoverableKeyException e) {
            e.printStackTrace();
        }
        System.out.println("URL :" + url);
        Gson gson = new Gson();
        HttpPost post = new HttpPost(url);
        try {
            pojoClass pojo1 = new pojoClass();
            pojo1.setUsername("Hello" + new Timestamp(new Date().getTime()));
            StringEntity postingString = new StringEntity(gson.toJson(pojo1));
            post.setEntity(postingString);
            post.setHeader("Content-type", "application/json");

            HttpResponse response = client.execute(post);
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            client.close();
        }
    }

    class pojoClass {
        private String username;

        public void setUsername(String username) {
            this.username = username;
        }
    }

    public CloseableHttpClient getHttpsClient() throws KeyStoreException, NoSuchAlgorithmException, CertificateException, IOException, KeyManagementException, UnrecoverableKeyException {

        ClassLoader classLoader = getClass().getClassLoader();
        String keystore_loc = "keystore.jks";
        String password = "password123";
        String truststore_loc = "cacerts";

        CloseableHttpClient returnHttpclient = null;
        KeyStore keyStore = KeyStore.getInstance("JKS");
        FileInputStream instream = new FileInputStream(getFile(keystore_loc));
        keyStore.load(instream, password.toCharArray());
        int timeout = 90000;
        RequestConfig config = RequestConfig.custom().setConnectTimeout(timeout).setConnectionRequestTimeout(timeout).setSocketTimeout(timeout).build();

        SSLContext sslcontext = SSLContexts.custom().loadKeyMaterial(keyStore, password.toCharArray()).loadTrustMaterial(
                getFile(truststore_loc), password.toCharArray(), new TrustSelfSignedStrategy()).build();
        SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(sslcontext, new String[]{"TLSv1.2"}, null,
                SSLConnectionSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);
        returnHttpclient = HttpClients.custom().setSSLSocketFactory(sslsf).setDefaultRequestConfig(config).build();

        return returnHttpclient;
    }

    public File getFile(String fileName) {
        URL resource = ClassLoader.getSystemClassLoader().getResource(fileName);

        if (resource == null) {
            throw new IllegalArgumentException("File is not available under resource dir !");
        } else {
            System.out.println(fileName + " : Reading the Certificate file from resource dir..." + resource);
            return new File(resource.getFile());
        }
    }

}

但是当我像下面这样阅读时,它可以工作。请有任何建议。

FileInputStream instream = new FileInputStream(new File("/home/rvp/keys/keystore.jks"));
4

1 回答 1

0

复制的密钥库对目标操作系统有错误的换行符。

于 2019-08-29T08:12:16.083 回答