SSL Client authentication in Android 4.x

∥☆過路亽.° 提交于 2019-12-05 05:31:57

You are never initializing a KeyManager with your private key, so there is no way client authentication can pick it up.

You'd have to implement X509KeyManager to return your PrivateKey and some hard-coded alias. Here's the one from the stock Email application (ICS+) for reference. You may need to modify it somewhat, but it should be easy to follow: basically it just saves the key, alias and certificate chain to fields and returns them via the appropriate methods (StubKeyManager just throws exceptions for the unimplemented and unneeded methods):

public static class KeyChainKeyManager extends StubKeyManager {
    private final String mClientAlias;
    private final X509Certificate[] mCertificateChain;
    private final PrivateKey mPrivateKey;

    public static KeyChainKeyManager fromAlias(Context context, String alias)
            throws CertificateException {
        X509Certificate[] certificateChain;
        try {
            certificateChain = KeyChain.getCertificateChain(context, alias);
        } catch (KeyChainException e) {
            logError(alias, "certificate chain", e);
            throw new CertificateException(e);
        } catch (InterruptedException e) {
            logError(alias, "certificate chain", e);
            throw new CertificateException(e);
        }

        PrivateKey privateKey;
        try {
            privateKey = KeyChain.getPrivateKey(context, alias);
        } catch (KeyChainException e) {
            logError(alias, "private key", e);
            throw new CertificateException(e);
        } catch (InterruptedException e) {
            logError(alias, "private key", e);
            throw new CertificateException(e);
        }

        if (certificateChain == null || privateKey == null) {
            throw new CertificateException("Can't access certificate from keystore");
        }

        return new KeyChainKeyManager(alias, certificateChain, privateKey);
    }

    private KeyChainKeyManager(
            String clientAlias, X509Certificate[] certificateChain, 
            PrivateKey privateKey) {
        mClientAlias = clientAlias;
        mCertificateChain = certificateChain;
        mPrivateKey = privateKey;
    }


    @Override
    public String chooseClientAlias(String[] keyTypes, Principal[] issuers, Socket socket) {
         return mClientAlias;
    }

    @Override
    public X509Certificate[] getCertificateChain(String alias) {
          return mCertificateChain;
    }

    @Override
    public PrivateKey getPrivateKey(String alias) {
            return mPrivateKey;
    }
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!