簡體   English   中英

使用我的自簽名證書創建KeyStore實例

[英]Create a KeyStore instance with my self signed certificate

我有一個用於與服務器通信的自簽名證書。 根據本文,我可以使用我的證書創建Keystore實例。 我做了同樣的事情,代碼工作得很好,我能夠通過HTTPS連接進行服務器調用。

當我打印密鑰庫中存在的所有證書時,它僅打印我已插入其中的證書。 我認為該實現將指示android信任AndroidCAStore中的所有內置證書以及服務器中的新自簽名證書。

創建實例時,我使用了AndroidCAStoreAndroidKeyStore但是問題是我無法將自簽名證書添加到密鑰庫中。 每當我調用setCertificateEntry我都會得到UnsupportedMethodException

我想創建一個KeyStore具有不同於Android的默認密鑰庫,並從我的服務器的自簽名證書的所有默認證書。 怎么做?

public static class CustomTrustManager implements X509TrustManager{

    private X509TrustManager defaultTrustManager;
    private X509TrustManager localTrustManager;

    public CustomTrustManager(KeyStore keyStore){
        try {
            defaultTrustManager = createTrustManager(null);
            localTrustManager = createTrustManager(keyStore);
        }catch (NoSuchAlgorithmException e){
            Log.e("CustomTrustManager"," Cannot create trust manager : NoSuchAlgorithm found "+e.toString());
        }catch (KeyStoreException exp){
            Log.e("CustomTrustManager"," Cannot create trust manager : Keystore exception"+e.toString());
        }
    }
    @Override
    public void checkClientTrusted(X509Certificate[] x509Certificates, String s) throws CertificateException {
        try {
            localTrustManager.checkClientTrusted(x509Certificates, s);
        } catch (CertificateException ce) {
            defaultTrustManager.checkClientTrusted(x509Certificates, s);
        }
    }

    @Override
    public void checkServerTrusted(X509Certificate[] x509Certificates, String s) throws CertificateException {
        Log.e("CustomTrustManager","Checking server trust");
        try {
            localTrustManager.checkServerTrusted(x509Certificates, s);
        } catch (CertificateException ce) {
            defaultTrustManager.checkServerTrusted(x509Certificates, s);
        }
    }

    @Override
    public X509Certificate[] getAcceptedIssuers() {
        X509Certificate[] first = defaultTrustManager.getAcceptedIssuers();
        X509Certificate[] second = localTrustManager.getAcceptedIssuers();
        X509Certificate[] result = Arrays.copyOf(first, first.length + second.length);
        System.arraycopy(second, 0, result, first.length, second.length);
        return result;
    }

    private X509TrustManager createTrustManager(KeyStore store) throws NoSuchAlgorithmException, KeyStoreException {
        String tmfAlgorithm = TrustManagerFactory.getDefaultAlgorithm();
        TrustManagerFactory tmf = TrustManagerFactory.getInstance(tmfAlgorithm);
        tmf.init((KeyStore) store);
        TrustManager[] trustManagers = tmf.getTrustManagers();
        return (X509TrustManager) trustManagers[0];
    }
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM