- Android – работа с ssl-сертификатами (как организовать передачу данных через HTTPS)
- 🤔Adding SSL Certificates into your Android App with Retrofit
- 🏁 Intro
- 📄 Let’s talk about the certificates
- 🥺 What is the difference?
- 😬 Give me the implementation!
- 🏃♂️ Let’s get started!
- 💻 The Code
- 🏆 Conclusion
- Installing a new trusted SSL root certificate on Android
- Jamie Holding
- What you need
- Step 1 — Setup the certificate
- Step 2 — Setup the device
- Sign up for more like this.
- Nursery Night Sky Feature Wall
- Manually Triggering Android Deep Links
Android – работа с ssl-сертификатами (как организовать передачу данных через HTTPS)
Что делать, если необходимо получать данные в андроиде через защищенное https-соединение? Почему генерируется ошибка SSLException: Not trusted server certificate ? Как добавить сертификат с сервера в локальное хранилище ключей на андроид-устройстве? Если вас волнуют эти вопросы – вам будет полезна инструкция для установки ssl сертификатов и сниппет кода для их загрузки в ваше андроид-приложение.
1. Как узнать, что за сертификат используется сервером (На Linux/Mac Os – как правило, пакет openssl предустановлен, для Windows – актуальные ссылки в разделе бинарниики там):
openssl s_client -connect :
для самоподписанных сертификатов выведется нечто вроде:
если используется сертификат, подписанный сторонней компанией – будут отображены координаты, по которым можно раздобыть публичный сертификат
2. Создаем файл сертификата
А). Для самоподписанного сертификата:
1. создать пустой файл my-certificate-file.pem
2. скопировать в новый файл закодированные данные сертификата:
да, открывающий\закрывающий теги должны быть.
Если сертификат самоподписанный можно использовать данный bash-script
echo | openssl s_client -connect :
2>/dev/null | sed -ne ‘/-BEGIN CERTIFICATE-/,/-END CERTIFICATE-/p’ > my-certificate-file.pem
Б). Если сертификат используемый сервером подписан сторонней организацией, на предыдущем шаге мы увидим ее контакты по которым его можно запросить. Почитать про разные типы сертификатов и попробовать онлайн-конвертер из одного типа в другой можно тут – https://www.sslshopper.com/ssl-converter.html
3. Создаем файл-хранилище с этим единственным ключом:
keytool -import -v -trustcacerts -alias myalias -file /bcprov-jdk16-146.jar -storepass
-alias myalias – псевдоним для работы с сертификатом
-keystore mystore.bks – говорим какой файл создать для хранения этого сертификата
-storetype BKS – android поддерживает такой тип хранилища, для того чтобы сгенерировать, его мы должны добавить в наш java CLASSPATH соответствующий jar-файл, последнюю версию которого можно взять отсюда – http://www.bouncycastle.org/latest_releases.html
для создания хранилища необходимо отдельно указать поставщика данного типа хранилища, а также путь к java-классу его реализующего.
(если этого не сделать появляется ошибка: keytool error: java.security.KeyStoreException: BKS not found )
4. Файл-хранилище мы можем добавить себе в проект чтобы использовать на этапе тестирования – например в папку assets. В обычном режиме работы, очевидно, его необходимо считывать из определенной директории для того чтобы работать с актуальной версией сертификата.
5. В android-приложении пригодится следующий сниппет кода:
1 этап – загружаем файл-хранилище с нашим сертификатом:
В реальном приложении, очевидно, файл необходимо будет считывать из предопределенной директории.
2 этап – создаем фабрику управления доверительными соединениями, она будет использоваться для проверки сертифкатов всех https соединений (я еще раз подчеркиваю – ВСЕХ)
После загрузки нашего хранилища ключей мы создаем фабрику для управления доверенными соединениями на основе этого хранилища. С помощью этой фабрики получаем экземпляр менеджера соединений специфичного для ssl (X509TrustManager) и инициализируем объект SSLContext, который будет использоваться для создания защищенного соединения.
3 этап – указываем какие настройки будут использоваться при установлении защищенных соединений:
После этого, если вы все сделали правильно, при каждом https соединении будут вызываться соотвествующие проверки, использующие подготовленный файл хранилище.
UPDATE 26.09.2012:
Хорошая статья по теме использования собственных сертификатов безопасности:
UPDATE 04.10.2012:
С помощью одной целеустремленной читательницы удалось приоткрыть завесу тайны над ошибкой: “SSL handshake terminated: ssl=0x1fcf30: Failure in SSL library, usually a protocol error” возникающей при попытке использовать двусторонюю аутентификацию – т.е. если не только клиент проверяет подлинность сервера но и сервер, проверяет что за клиент к нему лезет.
Источник
🤔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:
- Add our file into our project as a raw resource.
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.
- 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
Manually Triggering Android Deep Links
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
Источник