Jack M
Jack M

Reputation: 6015

How can I make all HTTP requests from my Android application accept a given certificate authority?

I have a server running HTTPS with a certificate from my own certificate authority. I have the CA certificate as a .pem file (for example, I can pass this to CURL with --cacert to get it to talk to my server).

I'm writing an Android application which will need to talk to this server. I need to be able to somehow give it this PEM file so that it will accept certs signed by my CA. This application is running in privileged mode on special purpose hardware and it is not possible to have the user add the cert itself through the Android settings UI, like you might do for a traditional app. I need to add the CA either programmatically in Java, or possibly at deployment time if that's easier (the software is deployed as a complete Android build).

I want to be able to add the CA in one place, and then any HTTPS requests made from the app will accept the CA, no matter what library or client they're made with. I don't want to go through the whole app configuring every request to accept the CA, we use several libraries and I don't want to have to figure out how to configure each one.

Note that I don't need the whole device to trust the CA necessarily, just my app.

Is this possible?

Upvotes: 0

Views: 2034

Answers (1)

Md. Asaduzzaman
Md. Asaduzzaman

Reputation: 15433

According documentation, The Network Security Configuration feature uses an XML file where you specify the settings for your app. You must include an entry in the manifest of your app to point to this file. The following code excerpt from a manifest demonstrates how to create this entry:

<?xml version="1.0" encoding="utf-8"?>
<manifest ... >
    <application android:networkSecurityConfig="@xml/network_security_config"
                    ... >
        ...
    </application>
</manifest>

res/xml/network_security_config.xml:

<?xml version="1.0" encoding="utf-8"?>
<network-security-config>
    <domain-config>
        <domain includeSubdomains="true">example.com</domain>
        <trust-anchors>
            <certificates src="@raw/my_ca"/>
        </trust-anchors>
    </domain-config>
</network-security-config>

Add your PEM certificate file to res/raw/my_ca.

Upvotes: 3

Related Questions