安卓中双向 SSL 认证

在 Python 服务器和 Android 客户端应用程序之间建立双向 SSL 认证。具备服务器和客户端的访问权限,希望使用自己的证书来实施客户端认证。截至目前,已能验证服务器证书并在不进行客户端认证的情况下进行连接。

想要了解客户端需要什么样的证书,以及如何在握手过程中让客户端自动将证书发送到服务器。怀疑可能使用了一个错误的文件来存放 CA 证书。

2. 解决方案

2.1 服务器端

需要让服务器信任客户端证书。通常的做法是创建一个 CA,然后让它对服务器证书和客户端证书进行签名。每个证书会在各自的信任库中拥有 CA 证书。然后,需要使用以下内容初始化 SSLContext:

KeyStore trustStore = loadTrustStore()
KeyStore keyStore = loadKeyStore()

TrustManagerFactory tmf = TrustManagerFactory
                    .getInstance(TrustManagerFactory.getDefaultAlgorithm())
tmf.init(trustStore)

KeyManagerFactory kmf = KeyManagerFactory
                    .getInstance(KeyManagerFactory.getDefaultAlgorithm())
kmf.init(keyStore, KEYSTORE_PASSWORD.toCharArray())

SSLContext sslCtx = SSLContext.getInstance("TLS")
sslCtx.init(kmf.getKeyManagers(), tmf.getTrustManagers(), null)

然后,可以使用 SSLContext 根据需要创建套接字工厂。它们将使用适当的密钥和证书进行初始化。

2.2 客户端

客户端需要设置客户端证书和服务器证书,并创建一个 SSLCertificateSocketFactory:

KeyStore keystore = KeyStore.getInstance("BKS"); // Stores the client certificate, to be sent to server
KeyStore truststore = KeyStore.getInstance("BKS"); // Stores the server certificate we want to trust
// TODO: change hard coded password... THIS IS REAL BAD MKAY
truststore.load(mSocketService.getResources().openRawResource(R.raw.truststore), "test".toCharArray());
keystore.load(mSocketService.getResources().openRawResource(R.raw.keystore), "test".toCharArray());

// Use the key manager for client authentication. Keys in the key manager will be sent to the host
KeyManagerFactory keyFManager = KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm());
keyFManager.init(keystore, "test".toCharArray());

// Use the trust manager to determine if the host I am connecting to is a trusted host
TrustManagerFactory trustMFactory = TrustManagerFactory.getInstance(TrustManagerFactory
                .getDefaultAlgorithm());
trustMFactory.init(truststore);

// Create the socket factory and add both the trust manager and key manager
SSLCertificateSocketFactory socketFactory = (SSLCertificateSocketFactory) SSLCertificateSocketFactory
                .getDefault(5000, new SSLSessionCache(mSocketService));
socketFactory.setTrustManagers(trustMFactory.getTrustManagers());
socketFactory.setKeyManagers(keyFManager.getKeyManagers());

// Open SSL socket directly to host, host name verification is NOT performed here due to
// SSLCertificateFactory implementation
mSSLSocket = (SSLSocket) socketFactory.createSocket(mHostname, mPort);
mSSLSocket.setSoTimeout(TIMEOUT);

// Most SSLSocketFactory implementations do not verify the server's identity, allowing man-in-the-middle
// attacks. This implementation (SSLCertificateSocketFactory) does check the server's certificate hostname,
// but only for createSocket variants that specify a hostname. When using methods that use InetAddress or
// which return an unconnected socket, you MUST verify the server's identity yourself to ensure a secure
// connection.
verifyHostname();
// Safe to proceed with socket now

2.3 验证主机名

验证主机名是可选的,但强烈建议进行验证。可以调用以下方法来完成此操作:

private void verifyHostname() {
        if (TextUtils.isEmpty(mHostname)) {
            return;
        }
        try {
            HostnameVerifier verifier = new HostnameVerifier() {

                @Override
                public boolean verify(String hostname, SSLSession session) {
                    // Check if hostname is the same or at least is an alias for the
                    // server's DNS name.
                    SNIHostnameVerifier hnv = new SNIHostnameVerifier();
                    return hnv.verify(hostname, session);
                }
            };
            HostnameVerifier hv = verifier;
            // Handshake may require check for host name --------------------
            if (!hv.verify(mHostname, mSSLSocket.getSession())) {
                throw new SSLPeerUnverifiedException("Matching host names with SSLSession.getPeerHost() failed.");
            }
        } catch (SSLException e) {
            boolean isSocketClosed = false;
            try {
                mSSLSocket.close();
                isSocketClosed = true;
            } catch (IOException ex) {
                Log.d(TAG, "Error while closing socket", ex);
            }
            if (isSocketClosed) {
                // Once the socket is closed, the thread will exit
                throw new RuntimeException(e);
            }
        }
    }
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值