How do I provide a specific TrustStore while using the default KeyStore in Java (JSSE)

后端 未结 2 1116
时光取名叫无心
时光取名叫无心 2021-01-06 02:52

Overview

JSSE allows users to provide default trust stores and key stores by specifying javax.net.ssl.* parameters. I would like to provide a non-default TrustMana

2条回答
  •  时光取名叫无心
    2021-01-06 03:32

    It's not too hard to write a KeyManager that has the default behaviour. It's only a few lines of code. It's surprising that SSLContexts don't all behave like that w.r.t. the KeyManager, as they do w.r.t. the TrustManager. IBM's JSSE does behave like that. But it's not hard to synthesize yourself:

    SSLContext  context = SSLContext.getInstance("TLS");
    String  keyStore = System.getProperty("javax.net.ssl.keyStore");
    String  keyStoreType = System.getProperty("javax.net.ssl.keyStoreType", KeyStore.getDefaultType());
    String  keyStorePassword = System.getProperty("javax.net.ssl.keyStorePassword","");
    KeyManager[]    kms = null;
    if (keyStore != null)
    {
        KeyManagerFactory   kmf = KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm());
        KeyStore    ks = KeyStore.getInstance(keyStoreType);
        if (keyStore != null && !keyStore.equals("NONE")) {
            fs = new FileInputStream(keyStore);
        ks.load(fs, keyStorePassword.toCharArray());
        if (fs != null)
            fs.close();
        char[]  password = null;
        if (keyStorePassword.length() > 0)
            password = keyStorePassword.toCharArray();
        kmf.init(ks,password);
        kms = kmf.getKeyManagers();
    }
    context.init(kms,null,null);
    

提交回复
热议问题