【问题标题】:Add cert file in retrofit request在改造请求中添加证书文件
【发布时间】:2021-06-01 08:53:56
【问题描述】:

我正在尝试将银行 API 集成到我的移动应用程序 (Android) 中,并且在沙盒模式下,我有一个公钥(证书)和一个私钥,每个请求都应该有。在 doc 中,请求如下所示:

curl -i -k --cert public.cert --cert-type PEM --key private.key --key-type PEM "endpoint.com" -H "Correlation-ID: OK1200" -H "WEB-API-Key: MY_API_KEY" -H "Authorization: Bearer MY_TOKEN"

那么,在沙盒模式下,我应该如何将私钥和公钥添加到我的改造请求中?

【问题讨论】:

  • 您是否测试过将证书文件放入raw 目录并将其加载到您的OkHttpClient.Builder 所在的位置? InputStream instream = context.getResources().openRawResource(R.raw.public);您可以从这种方法开始,然后提供有关您的进度的详细信息,以便人们可以实际提供帮助。

标签: android https request retrofit2 tls1.2


【解决方案1】:

您要做的是 TLS(传输层安全)实现。就安全应用程序而言,这是一个通常的过程。 如果您使用OkHttp 作为Retrofit 的网络客户端,您将能够相对容易地做到这一点,因为OkHttp 支持它开箱即用。 有几个选项,其中一个可以手动完成所有操作,但我不建议这样做。 相反,我会推荐 okhttp-tls 库,它正是为此而做的。 可能有一些细节,但通常,您的代码应如下所示:

// keyPair is a KeyPair(PublicKey, PrivateKey) where PublicKey and PrivateKey may be implemented via AndroidKeyStore
//certificate is X509Certificate which can bo obtained (X509Certificate)CertificateFactory.getInstance("X509").generateCertificate(assets.open("pathToCertificate.pem"))
HeldCertificate rootCertificate = HeldCertificate(keyPair, certificate);
HandshakeCertificates clientCertificates = new HandshakeCertificates.Builder()
    .addTrustedCertificate(rootCertificate.certificate())
    .build();
OkHttpClient client = new OkHttpClient.Builder()
    .sslSocketFactory(clientCertificates.sslSocketFactory(), clientCertificates.trustManager())
    .build();

【讨论】:

    猜你喜欢
    • 2018-08-15
    • 1970-01-01
    • 2022-12-13
    • 2015-08-27
    • 1970-01-01
    • 2016-11-20
    • 2018-05-17
    • 2016-12-16
    • 1970-01-01
    相关资源
    最近更新 更多