- Android Certificate: Generate, Sign And Verify An Apk App
- Looking At A Decompile APK File
- Generating An Android Certificate
- Method 1:
- Method 2:
- Method 3:
- Signing An Android Applicaiton
- Verifying An Android Application
- Как я могу проверить подлинность скачанного APK-файла?
- apksigner
- Usage
- Sign an APK
- Verify the signature of an APK
- Rotate signing keys
- Options
- Sign command
- General options
- Per-signer options
- Key and certificate options
- Verify command
- Examples
- Sign an APK
- Verify the signature of an APK
- Rotate signing keys
Android Certificate: Generate, Sign And Verify An Apk App
Apk signing has been a part of Android from the beginning of the Android evolution, and android requires all Apks should be signed before it can be installed on the device, There have been numerous articles regarding on how to generate a key and also how to sign an Apk, but we will be looking at it from a Security Perspective, After you decompile or reverse-engineer an Apk file, What file should you look into, To get more info about the Developer who originally sign the app.
Looking At A Decompile APK File
After you unzip the file or using apktool, depending on how you decompile the file, if you unzip the file, The file structure will look like this.
We are looking at the META-INF folder,
Looking at a decompile Apk using Apktool, It includes the certificates details about the developer and the type of hashing algorithm used and so on in the original folder and checking the META-INF folder.
Using keytool to check for the certificate while you are still currently in the META-INF folder.
depending on the name of your certificate alias name, You will see different information of the Owner, Country, Issuer, Certificate Validity from both the date the certificate is issue and when the certificate is set to be expired.
Certificate fingerprints in MD5, SHA1 and SHA256 and also the Signature algorithm used.
Before, I talk about Generating a certificate, lets look at it from security perspective, In analyzing an Android application which you download from third party web site, You can decompile the App and look at the certificate and compare it with the original App, Look at the hashing algorithm used, compare it if probably the application has been modified or tamper with, I wont be talking about analyzing an APK file but may be later.
Generating An Android Certificate
If you decompile your android application and compile it back, You will need to sign the app, and if you don’t sign it the Application wont be installed on the user device. There are different ways of generating a certificate but, we will look at three ways to generate a certificate using keytool.
Method 1:
Open your terminal:
where awwal — is the keystore name, alias — hafsa is the certificate alias name, which after you use it will be added to META-INF folder, -keysize 2048 , but you can use 4096 size, but there are issues regarding that from devices or so. but just use 2048, validity is in days.
Method 2:
Using apk-signer.jar which can be downloaded here https://shatter-box.com/knowledgebase/android-apk-signing-tool-apk-signer/
This is a GUI written in Java that allows generating a certificate and also signing an apk file. Though there’s also an Android App for that in Playstore.
Method 3:
I created a bash script that automate the task of using method 1, As method might require you installing Java Runtime, Just run the script i created which uses keytool and jarsigner.
Download the script here: https://github.com/ShehuAwwal/Apk-Signer
After that follow the instruction which will be prompted to generate your key.
Signing An Android Applicaiton
After you already generate your android application, we will look at how to sign the app, run your terminal:
Where -sigalg is the signature algorithm used, You can find some Apps using MD5 but use SHA1 as when you are verifying the app it will tell you the hashing algorithm used and how weak the algorithm used is.
keystore — awwal is the name of the keystore name used when generating the certificate, and hafsa is the alias name of the certificate, and medium.apk is the name of the app to be sign.
Note: if you MD5 the application will be treated as an unsign app because the algorithm use to sign the App is weak.
And the easier way is to use the Apk-signer.sh which i wrote to make the task easier.
Run the script, and press 2 for signing the app, Also completes also work there for file name and certificate name.
Or also you can make use of the apk-signer.jar also provide the options to sign the app.
Verifying An Android Application
Verify the app using jarsigner, to see the list of resources sign, the hashing algorithm with keysize.
Open your terminal:
where verify only will show either it is sign or unsign and using the verbose options to see the full details of the certificate.
Or you can use Apk-signer to verify the App with auto completion of file name.
Источник
Как я могу проверить подлинность скачанного APK-файла?
Последнее обновление Карт Google недоступно в моей стране, поэтому я скачал версию, найдя «Google Maps 5.4.0 apk». Я действительно нашел это, но теперь мне интересно, как я могу определить, действительно ли это та же версия, что и на рынке.
Как я могу быть уверен, что это не было подделано? Подписаны ли приложения каким-либо образом? Есть ли способ проверить подписи?
В дополнение к дискуссии о легитимности установки этого приложения на ваш телефон, вопрос проверки является тем, который я хотел понять некоторое время, и вы предложили мне попытаться выяснить возможный способ проверки того, кто подписал апк.
Приложения Android подписываются обычным образом .jar-файлами (на самом деле .apk — это просто специальный .jar, который является просто специальным .zip), однако проследить подлинность сертификатов, если у вас есть что-то хорошее по сравнению с. Это в основном то, что делает сам телефон — проверяет, что то, что, как утверждают, принадлежит той же стороне, что и то, что уже есть на телефоне, — телефон не отказывается устанавливать вещи с неизвестными подписчиками, он может только (возражать против / очищать приложение данные о) очевидных подделках, когда что-то новое не соответствует старому, на которое оно претендует.
Вам понадобится jarsigner и keytool. Я считаю, что они исходят от JDK, который является предпосылкой для Android SDK, а не сам SDK.
Сначала вы хотите проверить открытый ключ, содержащийся в .apk. Обычно это в META-INF / CERTS.RSA, но это может быть в другом файле — unzip -l скажет вам. Вы хотите увидеть, что вы можете узнать об этом:
Это даст много информации о том, кем подписчик утверждает. Некоторые сертификаты, очевидно, сами подписаны известными сторонами, но, не зная, как это отследить, я подозреваю, что вы могли бы сделать что-то вроде этого:
Если у вас есть известный доверенный apk от того же автора, который использовал тот же сертификат. Я предполагаю, что сертификатов с одинаковой суммой MD5 достаточно.
Предполагая, что вы решили доверять сертификату, вы сможете увидеть, использовался ли он для подписи каждого из файлов в .apk.
(Если в архиве более одного файла .RSA, вы должны добавить флаг -certs, чтобы указать, какие сертификаты использовались для подписи каждого файла, чтобы вы могли быть уверены, что это сертификат, который вы проверяли)
Источник
apksigner
The apksigner tool, available in revision 24.0.3 and higher of the Android SDK Build Tools, allows you to sign APKs and to confirm that an APK’s signature will be verified successfully on all versions of the Android platform supported by those APKs. This page presents a short guide for using the tool and serves as a reference for the different command-line options that the tool supports. For a more complete description of how the apksigner tool is used for signing your APKs, see the Sign your app guide.
Caution: If you sign your APK using apksigner and make further changes to the APK, the APK’s signature is invalidated. Therefore, you must use tools such as zipalign before signing your APK.
Usage
Sign an APK
The syntax for signing an APK using the apksigner tool is as follows:
When you sign an APK using the apksigner tool, you must provide the signer’s private key and certificate. You can include this information in two different ways:
- Specify a KeyStore file using the —ks option.
- Specify the private key file and certificate file separately using the —key and —cert options, respectively. The private key file must use the PKCS #8 format, and the certificate file must use the X.509 format.
Usually, you sign an APK using only one signer. In the event that you need to sign an APK using multiple signers, use the —next-signer option to separate the set of general options to apply to each signer:
Verify the signature of an APK
The syntax for confirming that an APK’s signature will be verified successfully on supported platforms is as follows:
Rotate signing keys
The syntax for rotating a signing certificate lineage, or a new sequence of signatures, is as follows:
Options
The following lists include the set of options for each command that the apksigner tool supports.
Sign command
General options
The following options specify basic settings to apply to a signer:
—out The location where you’d like to save the signed APK. If this option isn’t provided explicitly, the APK package is signed in-place, overwriting the input APK file. —min-sdk-version The lowest Android framework API level that apksigner uses to confirm that the APK’s signature will be verified. Higher values allow the tool to use stronger security parameters when signing the app but limit the APK’s availability to devices running more recent versions of Android. By default, apksigner uses the value of the minSdkVersion attribute from the app’s manifest file. —max-sdk-version The highest Android framework API level that apksigner uses to confirm that the APK’s signature will be verified. By default, the tool uses the highest possible API level. —v1-signing-enabled
Per-signer options
The following options specify the configuration of a particular signer. These options aren’t necessary if you sign your app using only one signer.
—next-signer Used for specifying different general options for each signer. —v1-signer-name The base name for the files that comprise the JAR-based signature for the current signer. By default, apksigner uses the key alias of the KeyStore or the basename of the key file for this signer.
Key and certificate options
The following options specify the signer’s private key and certificate:
—ks The signer’s private key and certificate chain reside in the given Java-based KeyStore file. If the filename is set to «NONE» , the KeyStore containing the key and certificate doesn’t need a file specified, which is the case for some PKCS #11 KeyStores. —ks-key-alias The name of the alias that represents the signer’s private key and certificate data within the KeyStore. If the KeyStore associated with the signer contains multiple keys, you must specify this option. —ks-pass
The password for the KeyStore that contains the signer’s private key and certificate. You must provide a password to open a KeyStore. The apksigner tool supports the following formats:
– Password provided inline with the rest of the apksigner sign command.
Note: If you include multiple passwords in the same file, specify them on separate lines. The apksigner tool associates passwords with an APK’s signers based on the order in which you specify the signers. If you’ve provided two passwords for a signer, apksigner interprets the first password as the KeyStore password and the second one as the key password.
—pass-encoding Includes the specified character encodings (such as, ibm437 or utf-8 ) when trying to handle passwords containing non-ASCII characters.
Keytool often encrypts keystores by converting the password using the console’s default charset. By default, apksigner tries to decrypt using several forms of the password: the Unicode form, the form encoded using the JVM default charset, and, on Java 8 and older, the form encoded using the console’s default charset. On Java 9, apksigner cannot detect the console’s charset. So, you may need to specify —pass-encoding when a non-ASCII password is used. You may also need to specify this option with keystores that keytool created on a different OS or in a different locale.
The password for the signer’s private key, which is needed if the private key is password-protected. The apksigner tool supports the following formats:
– Password provided inline with the rest of the apksigner sign command.
Note: If you include multiple passwords in the same file, specify them on separate lines. The apksigner tool associates passwords with an APK’s signers based on the order in which you specify the signers. If you’ve provided two passwords for a signer, apksigner interprets the first password as the KeyStore password and the second one as the key password.
Verify command
Examples
Sign an APK
Sign an APK using release.jks , which is the only key in the KeyStore:
Sign an APK using a private key and certificate, stored as separate files:
Sign an APK using two keys:
Verify the signature of an APK
Check whether the APK’s signatures are expected to be confirmed as valid on all Android platforms that the APK supports:
Check whether the APK’s signatures are expected to be confirmed as valid on Android 4.0.3 (API level 15) and higher:
Rotate signing keys
Enable a signing certificate lineage that supports key rotation:
Rotate your signing keys again:
Content and code samples on this page are subject to the licenses described in the Content License. Java is a registered trademark of Oracle and/or its affiliates.
Источник