java - path to trustStore - set property 不起作用?

2022-08-31 20:04:55

我已经设置了一个自签名证书来测试ssl java连接 - 但是,它拒绝找到java trustStore。我已经在/Java/jre6/lib/security中保存了它的副本,除了将类编译到的文件夹(im使用netbeans)以及/java/jre6/bin,上述内容似乎都不起作用,因为当我运行以下命令时 - trustStore = null。

public class ShowTrustStore {

    public static void main(String[] args) {

        System.setProperty("javax.net.ssl.keyStore", "keystore.jks");
        System.setProperty("javax.net.ssl.trustStrore", "cacerts.jks");
        System.setProperty("javax.net.ssl.keyStorePassword", "changeit");



        String trustStore = System.getProperty("javax.net.ssl.trustStore");
        if (trustStore == null) {
            System.out.println("javax.net.ssl.trustStore is not defined");
        } else {
            System.out.println("javax.net.ssl.trustStore = " + trustStore);
        }
    }
}

如何正确设置路径?

UPDATE************ 使用 getFile() 方法和更多调试数据:

package ssltest;

public class Main {

    public static void main(String[] args) {

//        System.setProperty("javax.net.ssl.keyStore", "/keystore.jks");
//        System.setProperty("javax.net.ssl.trustStrore", "/java.home/cacerts.jks");
//        System.setProperty("javax.net.ssl.keyStorePassword", "changeit");
//        System.setProperty("javax.net.ssl.trustStorePassword", "changeit");

        try {
            Main.class.getResource("trustStore.jks").getFile();
        } catch (Exception e) {
            e.printStackTrace();
        }

        String trustStore = System.getProperty("javax.net.ssl.trustStore");

        if (trustStore == null) {
            String storeLoc;
            storeLoc = System.getProperty("java.class.path");
            System.out.println("classpath: " + storeLoc);
        }

        trustStore = System.getProperty("javax.net.ssl.trustStore");
        if (trustStore == null) {
            System.out.println("javax.net.ssl.trustStore is not defined");
        } else {
            System.out.println("javax.net.ssl.trustStore = " + trustStore);
        }
    }
}

run: java.lang.NullPointerException classpath: C:\Users\Main\Documents\NetBeansProjects\sslTest\build\classes;C:\Users\Main\Documents\NetBeansProjects\sslTest\src at ssltest.Main.main(Main.java:15) javax.net.ssl.trustStore 未定义 构建成功 (总时间: 0 秒)


答案 1

你有一个错别字 - 它是.trustStore

除了设置变量之外,您还可以使用System.setProperty(..)

-Djavax.net.ssl.keyStore=path/to/keystore.jks

答案 2

看起来你有一个错别字 - “trustStrore”应该是“trustStore”,即

System.setProperty("javax.net.ssl.trustStrore", "cacerts.jks");

应该是:

System.setProperty("javax.net.ssl.trustStore", "cacerts.jks");