1

我有无需改装即可使用的证书:

public static Certificate loadCertificateFromRaw(String name) {
    Certificate certificate = null;
    InputStream caInput = null;

    try {
        CertificateFactory cf = CertificateFactory.getInstance("X.509");
        caInput = GlobalFunctions.class.getClassLoader().getResourceAsStream("assets/" + name);
        certificate = cf.generateCertificate(caInput);
        System.out.println("ca=" + ((X509Certificate) certificate).getSubjectDN());
    } catch(Exception e) {
        e.printStackTrace();
    } finally {
        if (caInput != null) {
            try {
                caInput.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    return certificate;
}

现在我们开始改造,我正在尝试复制这个实现

我发现这篇文章: https ://medium.com/yellowme/adding-ssl-certificates-into-your-android-app-with-retrofit-1a6ea9bd3b27

但我不想创建密钥和更多我不需要的东西。

像以前一样添加这个 *.crt 文件

这是我找到的代码,你可以看到它有比我需要的更多的东西,但它们彼此相关,所以我不知道如何删除我不需要的东西

caFileInputStream  = context.resources.openRawResource(R.raw.root_crt)
// Here you may wanna add some headers or custom setting for your builder

// We're going to put our certificates in a Keystore
val keyStore = KeyStore.getInstance("PKCS12")
keyStore.load(caFileInputStream, "my file password".toCharArray())

// Create a KeyManagerFactory with our specific algorithm our our public keys
// Most of the cases is gonna be "X509"
val keyManagerFactory = KeyManagerFactory.getInstance("X509")
keyManagerFactory.init(keyStore, "my file password".toCharArray())

// Create a SSL context with the key managers of the KeyManagerFactory
val sslContext = SSLContext.getInstance("TLS")
sslContext.init(keyManagerFactory.keyManagers, null, SecureRandom())

//Finally set the sslSocketFactory to our builder and build it
return httpClientBuilder.sslSocketFactory(sslContext.socketFactory).build()
4

0 回答 0