无需中介的 OkHttp 客户端证书

时间:2021-02-10 17:19:21

标签: okhttp mutual-authentication

我正在尝试使用 okhttp 对服务器进行身份验证。

使用 curl 会这样:

curl \
--cert certificate.cer \
--key private-key.pkcs8 \
"https://some-url"

不幸的是,okhttp-tls 似乎总是期望除了持有的证书之外还有一系列证书,而我没有。

heldCertificate 期望证书链,除了 clientCertificate,与 reame 中提供的示例相反:

HandshakeCertificates clientCertificates = new HandshakeCertificates.Builder()
    .addTrustedCertificate(rootCertificate.certificate())
    .heldCertificate(clientCertificate) // <--------------------
    .build();

如何将 okhttp 与单个证书和我的私钥一起使用?

1 个答案:

答案 0 :(得分:0)

heldCertificates 期待可能存在于客户端证书(匹配私钥)和直到但不包括服务器已知信任的根 CA 之间的中间链。因此,如果不需要其他证书,则可以省略这一点。

https://square.github.io/okhttp/4.x/okhttp-tls/okhttp3.tls/-handshake-certificates/-builder/held-certificate/

<块引用>

配置认证时使用的证书链。这 第一个证书是持有的证书,其他证书是 包含在握手中,以便对等方可以建立到一个可信的路径 受信任的根证书。

该链应包括所有中间证书,但不包括 需要我们希望远程知道的根证书 同行。对等方已经拥有该证书,因此传输它是 没有必要。

以下是一些使用自签名证书(如果已知服务器已经信任)的示例,以及用于根据所连接的主机切换使用的密钥的示例。您需要根据您的确切设置调整这些设置,但它们应该为您提供一个测试起点。

https://github.com/square/okhttp/pull/6470/files