Android how to install certificate

🤔Adding SSL Certificates into your Android App with Retrofit

When this task was assigned to me in the project I’m working, I thought: this will be easy and it was 🙂, but it wasn’t 🙃, because I didn’t find a lot of posts on how to add my certificate.

You can always read the Official Android SSL Documentation (you should), but the implementation wasn’t clear enough to me, so I decided to create this post to simplify it for anyone who is going through the same problem 👍.

🏁 Intro

In this post I’m going to explain how to add certificates to our Android app when we have a .pfx file, not only the .crt , and of course, it will include a brief explanation of what those files are.

So after reading this tutorial we’re going to be familiarized with:

This tutorial is going to be based on a project using Retrofit to make calls to an API, but you can always adapt it for your specific case.

📄 Let’s talk about the certificates

A certificate authority (CA) is a company or organization that acts to validate the identities of entities (such as websites, email addresses, companies, or individual persons) and bind them to cryptographic keys through the issuance of electronic documents known as digital certificates.

So basically the CAs give us a way to authenticate us by serving as credentials to validate our identity, encrypt our data for secure communication over the insecure networks such as the internet, and give us a way to be sure nothing has been altered by a third party in transit because of the signature of the certificate.

Typically, an applicant for a digital certificate will generate a key pair consisting of a private key and a public key, along with a certificate signing request (CSR). A CSR is an encoded text file that includes the public key and other information that will be included in the certificate (e.g. domain name, organization, email address, etc.). Key pair and CSR generation are usually done on the server or workstation.

The .crt and the .pfx files are CSR encoded.

🥺 What is the difference?

CER (or .CRT) files: CER file is used to store X.509 certificate. Normally used for SSL certification to verify and identify web servers security. The file contains information about certificate owner and public key.

PFX files: Personal Exchange Format, is a PKCS12 file. This contains a variety of cryptographic information, such as certificates, root authority certificates, certificate chains and private keys. It’s cryptographically protected with passwords to keep private keys private and preserve the integrity of the root certificates.

Basically, the PFX contains more information than the CRT.

😬 Give me the implementation!

Okay, if you already know something about the CAs you probably just want to know how to implement them. So, let’s get into it.

If you have tried to add your certificate with a .crt file and Retrofit, you may have found this class in some post or documentation. I’m actually going to use code of that class for the implementation, but I’m going to break it down for easier reading, and to show the small changes we need to add when we’re using a .pfx file so you can use whichever you need.

The source code is gonna be at the end of the post.

🏃‍♂️ Let’s get started!

In order to add our certificates we’re going to create a method that generates an OkHttpClient. We only need to follow these simple steps:

  1. Add our file into our project as a raw resource.
Читайте также:  Автомагнитола андроид для тойоты рав 4

2. Create a method that returns an OkHttpClient .

3. Create a KeyStore containing our trusted CAs.

5. Create an SSL Context that contains our trusted CAs.

6. Add our socket factory to our builder.

7. Use the generated OkHttpClient as usual.

  1. Add our file into our project as a raw resource (in the raw folder).

We can just drag and drop the file into the raw folder or go to our project directory and create it inside the app/src/main/res and then paste our file.

2. Create a method that returns an OkHttpClient .

This method is where we’re going to add our certificate to our OkHttpClient so we can use it to make calls to an API. In this example, I’m going to simplify, but you can always add custom settings.

3. Create a KeyStore containing our trusted CAs.

The KeyStore class is going to help us to store our certificates, but the type of instance is very important, that’s going to make the difference between using a .crt file or a .pfx .

.CRT → the default type is gonna work for you. KeyStore.getInstance(KeyStore.getDefaultType())

.PFX → you need to use PKCS12, this is a special format to place the certificate (includes its “intermediate”) with the private key.
KeyStore.getInstance(«PKCS12»)

The password is the one you need to use when you want to read your file. In this code I’m setting it as a String , but you should always keep it secure, so you better use a file with it or as a Build Config Field.

4. Create a KeyManagerFactory so we can have keyManagers with the algorithm of our certificate.

We’re getting an instance of an X509 Factory because that’s the standard of my public key certificate and it’s the most used one.

5. Create an SSL Context that contains our trusted CAs.

In this case we’re using an instance of a TLS Context because our server required so, and as TLS is basically a newer version of SSL we can use it as default.

6. Finally, add our socket factory to our builder.

Just use the socketFactory of the sslContext that we created in the last step and set it to the builder.

7. Use the generated OkHttpClient as usual.

Now that we added our trusted CAs to an OkHttpClient we can proceed to use it with a Retrofit instance as usual.

And just like that we’ll be able to make some calls to our API 🎉.

💻 The Code

🏆 Conclusion

Adding our trusted CAs in our Android app is not complicated and can be very useful when we have multiple flavors or build types with different API environments and some of those are secured with a CA.

Remember to remove your Development certificate when you’re building a Release version of your app; you don’t wanna give it away 😅. I also suggest deleting the file from Git for security reasons.

This post was made to try to simplify the explanation of the implementation that you probably are gonna find on the internet.

Источник

Installing a new trusted SSL root certificate on Android

Jamie Holding

It’s very trivial to install a user-trusted certificate on android. Under Settings -> Security you can install new trusted certificates. However, this creates a permanent «Your network could be monitored» warning in your task tray and forces you to have a lock-screen. In addition to this, in newer versions of Android, Android apps will by default only trust system certificates.

By default, apps that target API level 24 will—by design—not honor such CAs unless the app explicitly opts in.

So, ultimately if you want to be keeping an eye on what your phone is up to, you’re going to need to install a system trusted certificate come Android 7.0 onwards.

This setup is largely inspired from http://wiki.pcprobleemloos.nl/android/cacert — but without the endless references to cacert, which we aren’t using.

What you need

  • A rooted Android phone
  • ADB setup and ready to go
  • An SSL certificate in PEM form ** If you are using Charles Proxy, go to charlesproxy.com/getssl to download your certificate from your proxy in PEM form
  • OpenSSL command line tools ** On Linux, Google how to install for your distro ** On Windows, either setup Bash for Windows 10, or install OpenSSL and add the executable to your PATH environment variables
Читайте также:  Гугл инсталлер для андроид что это

Step 1 — Setup the certificate

If your certificate isn’t in .PEM form, convert it from whatever format you currently have it in into .PEM first.

As an example, if you have it in .CER format, use openssl x509 -inform der -in cert.cer -out cert.pem to get it into .PEM.

You need to find the hash of your certificate first. To do this, run the following command on your certificate (mine is called cert.pem, replace as needed):

You should get something like 5h543h5a.

Write our .pem certificate to a new file with the hash name from above and the file extension .0 (replacing the hash with the result you had from above):

Now we need to export the PEM information into the bottom of this new file.

Now you have your .0 file ready for adding to the Android device!

Step 2 — Setup the device

Have the device plugged in and make sure you’ve enabled ADB debugging.

Run the following to make sure we’re debugging as root on the device:

If you have any issues here, you might need to enable root ADB in the developer options on the device. Google if you have other issues and then come back here when you’re set!

Now you probably need to remount your device to get access to the system files for writing our certificate.

Push your new file to your device in the system certificates folder.

Now open the shell by running adb shell and then run the following command to set the correct file permissions:

Now reboot the phone and if you go to Settings -> Security you should be able to find your new system trusted certificate!

Sign up for more like this.

Nursery Night Sky Feature Wall

My little baby girl is on her way (probably here by the time I publish this). We knew we wanted to theme her nursery to something cool. At one point it was going to be dinosaurs, because dinosaurs are awesome. But that sounded complicated and we are really after subtle

Sometimes it’s handy to test triggering a mobile deep link to test some new integration. You may have tried typing the URL into your phone’s web browser (like Chrome) to trigger the app launching, however this doesn’t work! The link needs to be clicked to trigger. However, instead of creating

Источник

Установка собственного корневого сертификата в Android и запуск Citrix XenApp Web Interface

В принципе, мы с shoguevara довольно давно заморачивались вопросом установки корневого сертификата в Android устройство и даже находили парочку не самых тривиальных инструкций, но до этого в таком действии надобности не было. Надобность же появилась после приобретения планшета на Android.

Немножко предыстории:

Стоит у нас в конторе Citrix XenApp для обеспечения удалённой работы из офиса. Что это за зверь и с чем его едят рассказывать не будем — кому это надо, те давно в курсе.
В этой совместной с записи мы хотим рассказать об установке корневого сертификата и настройке клиентской части — Citrix Receiver для Android.

В принципе, клиент не самый убогий — пользоваться можно, а если Вы где-то в поездке, а на руках только телефон на Android или планшет — это единственный выход для быстрого подключения и исправления что-либо через рабочий компьютер.
Вроде бы софтина не особо мудрёная да и настроек особо много не требует, а если Вы используете веб-интерфейс для запуска приложений, как это сделано в нашей организации, то и совсем никаких…
Но не все бывает так безоблачно!

Что же за проблемы могли возникнуть?

Для организации такого рода архитектуры удалённого доступа довольно часто используются сертификаты, которые подписаны центрами не входящими в список стандартных. Почему Google такие нехорошие, и не включили в свою ОСь такую простую функцию, (наряду с такой, опять же, нужной функцией, как возможность прописать прокси-сервер) как установка дополнительных корневых сертификатов ЦА, тут мы обсуждать не собираемся.
Первым признаком того, что сервер использует самоподписанный сертификат является то, что, когда Вы открываете, откуда бы то ни было веб-ресурс с помощью, например, браузера Mozilla Firefox, программа выдает сообщение о том, что не может сама принять решение о том доверять ли сертификату для установления защищённого соединения или нет — она предоставляет право выбора Вам.
Если у вас наблюдается такая картина, то эта статья как раз для Вас!

Читайте также:  Android studio find method

Так что же все-таки надо, чтобы запустить через Citrix Receiver приложения опубликованные на Citrix XanApp вашего предприятия?

В первую очередь, как оказалось, необходимо установить Mozilla Firefox для Android. Очень странно, но ни один другой браузер не передаёт нужный для подключения файл (launch.ica) в программу-клиент. Знаем только то, что с Firefox все работает нормально.

Во вторую очередь нужна сама программа-клиент. Тут на Android Market у нас есть выбор: стабильный Citrix Receiver, либо находящийся на этапе тестирования Citrix Labs Receiver. Второй у нас не захотел принимать сертификат ни в какую, первый же — стабильный, после бессонной ночи таки у нас и заработал.

В-третьих, необходимо иметь root-доступ к вашему устройству, либо возможность извлекать и записывать обратно файлы через adb, хотя, в этом случае тоже требуется root-доступ (как его настроить Вы сможете узнать потратив немного времени на просмотр результатов, который выдал вам Google на запрос вида » root access howto» или » adb configure howto»).

Вопросом настройки adb мы заморачиваться, опять таки, не стали, так как предпочитаем работать напрямую через файл-менеджеры с системой. В любом случае, в сети довольно много информации по этому поводу (русскоязычный ресурс, на котором больше всего информации такого плана — http://4pda.ru/forum, англоязычный — http://forum.xda-developers.com). В случае, если Вы будете использовать прямой доступ к системным файлам, то нужен файловый менеджер, который умеет использовать root-права (например, Root Explorer).

В-четвертых, нужна машина с любым из популярных Linux-дистрибутивов и установленной Java-машиной от Oracle (мы использовали Ubuntu 10.10 с установленным JRE).

И последнее в списке, но далеко не последнее по значимости — сам корневой сертификат центра сертификации (пусть он будет называться CompanyCA.crt).

От требований (если они все выполнены) переходим к действию.

Для удобства будем перечислять все по пунктам.

1. Заходим с устройства на Android Market и устанавливаем Firefox.
2. Заходим с устройства на Android Market и устанавливаем Citrix Receiver.
3.1.1 (3.1.х для тех кто предпочитает прямой доступ) С помощью файлового менеджера копируем файл /system/etc/security/cacerts.bks cacerts.bks на карту SD.
3.1.2 Подключаем устройство как накопитель к компьютеру с Linux.
3.1.3 Копируем файл cacerts.bks с корня карточки в вашу домашнюю папку.
3.2.1 (adb) копируем сертификат
$ adb pull /system/etc/security/cacerts.bks cacerts.bks

4. Этот пункт предполагает, что Вы уже установили и настроили JRE 1.6 и прописана переменная окружения JAVA_HOME (в моем случае JAVA_HOME=/usr/lib/jvm/java-6-sun/).
Скачиваем пакет bouncycastle.org/download/bcprov-jdk16-146.jar и кидаем его в папку $JAVA_HOME/jre/lib/ext/
Если у вас установлен JDK, то этот пакет, надо так же закинуть в папку /usr/lib/jvm/java-6-openjdk/jre/lib/ext
wget bouncycastle.org/download/bcprov-jdk16-146.jar
sudo cp bcprov-jdk16-146.jar $JAVA_HOME/jre/lib/ext/bcprov-jdk16-146.jar
# или sudo cp bcprov-jdk16-146.jar /usr/lib/jvm/java-6-sun/jre/lib/ext/bcprov-jdk16-146.jar

5. Кидаем файл сертификата CompanyCA.crt так же в домашнюю папку. Если его у Вас нет, но Вы соглашались принять сертификат при переходе на веб-интерфейс XenApp, то его можно экспортировать из Firefox. Как это сделать — подскажет Google. Можем лишь уточнить, что шифрование нужно X.509 PEM.

6. Скачиваем и устанавливаем Android SDK (если Вы не планируете использовать adb, то этот шаг можно пропустить):
wget dl.google.com/android/android-sdk_r10-linux_x86.tgz
tar -xvzf android-sdk_r10-linux_x86.tgz
sudo mv android-sdk-linux_x86 /usr/lib/android-sdk-linux_x86
Запускать что-либо из комплекта для нашей задачи не требуется. Но нужно прописать исполняемые файлы SDK в переменных окружения export PATH=$:/usr/lib/android-sdk-linux_x86/tools.
В нашем случае вопрос с переменными окружения решается добавлением в конец файла

/.bashrc строчек
export PATH=$:/usr/lib/android-sdk-linux_x86/tools
export JAVA_HOME=/usr/lib/jvm/java-6-sun/jre

7. Открываем консоль и выполняем команду
keytool -keystore cacerts.bks -storetype BKS -provider org.bouncycastle.jce.provider.BouncyCastleProvider -storepass changeit -importcert -trustcacerts -alias CACERT -file CompanyCA.crt

Будьте внимательны — не меняйте параметр -storepass changeit, там действительно такой пароль)

В ответ на эту команду Вы должны получить информацию о сертификате и запрос «Trust this certificate? [no]: » — соответственно отвечаем «y».
Все, наш файл подготовлен. Теперь нужно загрузить его на устройство.

8.1.1 (прямой доступ) Подключаем устройство как накопитель к компьютеру;
8.1.2 Загружаем на карту файл cacerts.bks;
8.1.3 Переносим с помощью менеджера файлов cacerts.bks из папки /sdcard в папку /system/etc/security/, предварительно примонтировав её для записи;
8.2.1 (adb) Монтируем систему для записи:
$ adb shell mount -o remount,rw /system;
8.2.2 Загружаем файл:
$ adb push cacerts.bks /system/etc/security/;
8.2.2 Монтируем систему только для чтения:
$ adb shell mount -o remount,ro /system.

На этом трудная часть пройдена. Осталась пара «финтов ушами».

9. Перезагружаем устройство.

10. Запускаем Firefox и открываем страницу веб-доступа.
Появится приблизительно такая картина:

Тут нам надо нажать на ссылку «Already installed» в верхней части экрана;

11. Выбираем приложение из списка и пробуем запустить;

Источник

Оцените статью