How to sign apk

How to sign apk

How to sign an apk through command line

Be informed that we have created an apk file through command line with the help of Android SDK. Now since uploading it to google play store needs the apk to be signed. How shall we do this.

3 Answers 3

Trending sort

Trending sort is based off of the default sorting method — by highest score — but it boosts votes that have happened recently, helping to surface more up-to-date answers.

It falls back to sorting by highest score if no posts are trending.

Switch to Trending sort

Step 1

First you need to generate a private signing key

This command will prompt you for a password for your keystore and key (also for some additional fields). Please remember to keep your keystore file private at anytime.

Step 2

Next you need to setup gradle

/.gradle/gradle.properties under android/app and add the following

Step 3

Now you can simply generate a signed release via the command line by running the following command in your android directory

The generated apk can then be found under your build/outputs/apk/release directory.

First you need a keystore to begin the process. You will be signing your apk with this keystore and you need to sign with same keystore for future updates. Know more about keystore here: https://developer.android.com/studio/publish/app-signing#generate-key

Once you generate the keystore, you should jarsigner utility (which is available in JDK folder)

PS: Replace paths, files and passwords with actual values

Manually Signing the APK

After the application has been built for release, the APK must be signed prior to distribution so that it can be run on an Android device. This process is typically handled with the IDE, however there are some situations where it is necessary to sign the APK manually, at the command line. The following steps are involved with signing an APK:

Create a Private Key – This step needs to be performed only once. A private key is necessary to digitally sign the APK. After the private key has been prepared, this step can be skipped for future release builds.

Zipalign the APK – Zipalign is an optimization process that is performed on an application. It enables Android to interact more efficiently with the APK at runtime. Xamarin.Android conducts a check at runtime, and will not allow the application to run if the APK has not been zipaligned.

Sign the APK – This step involves using the apksigner utility from the Android SDK and signing the APK with the private key that was created in the previous step. Applications that are developed with older versions of the Android SDK build tools prior to v24.0.3 will use the jarsigner app from the JDK. Both of these tools will be discussed in more detail below.

The order of the steps is important and is dependent on which tool used to sign the APK. When using apksigner, it is important to first zipalign the application, and then to sign it with apksigner. If it is necessary to use jarsigner to sign the APK, then it is important to first sign the APK and then run zipalign.

Prerequisites

This guide will focus on using apksigner from the Android SDK build tools, v24.0.3 or higher. It assumes that an APK has already been built.

Applications that are built using an older version of the Android SDK Build Tools must use jarsigner as described in Sign the APK with jarsigner below.

Create a Private Keystore

A keystore is a database of security certificates that is created by using the program keytool from the Java SDK. A keystore is critical to publishing a Xamarin.Android application, as Android will not run applications that have not been digitally signed.

During development, Xamarin.Android uses a debug keystore to sign the application, which allows the application to be deployed directly to the emulator or to devices configured to use debuggable applications. However, this keystore is not recognized as a valid keystore for the purposes of distributing applications.

For this reason, a private keystore must be created and used for signing applications. This is a step that should only be performed once, as the same key will be used for publishing updates and can then be used to sign other applications.

It is important to protect this keystore. If it is lost, then it will not be possible to publish updates to the application with Google Play. The only solution to the problem caused by a lost keystore would be to create a new keystore, re-sign the APK with the new key, and then submit a new application. Then the old application would have to be removed from Google Play. Likewise, if this new keystore is compromised or publicly distributed, then it is possible for unofficial or malicious versions of an application to be distributed.

Create a New Keystore

Creating a new keystore requires the command line tool keytool from the Java SDK. The following snippet is an example of how to use keytool (replace with the file name for the keystore and with the name of the key within the keystore):

The first thing that keytool will ask for is the password for the keystore. Then it will ask for some information to help with creating the key. The following snippet is an example of creating a new key called publishingdoc that will be stored in the file xample.keystore :

To list the keys that are stored in a keystore, use the keytool with the – list option:

Zipalign the APK

Before signing an APK with apksigner, it is important to first optimize the file using the zipalign tool from the Android SDK. zipalign will restructure the resources in an APK along 4-byte boundaries. This alignment allows Android to quickly load the resources from the APK, increasing the performance of the application and potentially reducing memory use. Xamarin.Android will conduct a run-time check to determine if the APK has been zipaligned. If the APK is not zipaligned, then the application will not run.

The follow command will use the signed APK and produce a signed, zipaligned APK called helloworld.apk that is ready for distribution.

Sign the APK

After zipaligning the APK, it is necessary to sign it using a keystore. This is done with the apksigner tool, found in the build-tools directory of the version of the SDK build tools. For example, if the Android SDK build tools v25.0.3 is installed, then apksigner can be found in the directory:

The following snippet assumes that apksigner is accessible by the PATH environment variable. It will sign an APK using the key alias publishingdoc that is contained in the file xample.keystore:

When this command is run, apksigner will ask for the password to the keystore if necessary.

See Google’s documentation for more details on the use of apksigner.

According to Google issue 62696222, apksigner is «missing» from the Android SDK. The workaround for this is to install the Android SDK build tools v25.0.3 and use that version of apksigner.

Sign the APK with jarsigner

This section only applies if it is nececssary to sign the APK with the jarsigner utility. Developers are encouraged to use apksigner to sign the APK.

This technique involves signing the APK file using the jarsigner command from the Java SDK. The jarsigner tool is provided by the Java SDK.

The following shows how to sign an APK by using jarsigner and the key publishingdoc that is contained in a keystore file named xample.keystore :

When using jarsigner, it is important to sign the APK first, and then to use zipalign.

Подписывание пакета APK вручную

После сборки приложения для выпуска и до распространения необходимо подписать пакет APK, чтобы его можно было запускать на устройстве Android. Как правило, этот процесс обрабатывается в интегрированной среде разработки, однако существуют ситуации, когда пакет APK нужно подписать вручную с использованием командной строки. В ходе процесса подписывания пакета APK выполняются следующие действия:

Zipalign APKZipalign — это процесс оптимизации, выполняемый в приложении. Он позволяет Android более эффективно взаимодействовать с пакетом APK во время выполнения. Xamarin.Android проводит проверку во время выполнения и запретит запуск приложения, если пакет APK не был оптимизирован.

Важно соблюдать порядок действий, который зависит от средства, применяемого для подписывания пакета APK. При использовании apksigner важно сначала оптимизировать приложение с помощью zipalign, а затем подписать его с помощью apksigner. Если для подписывания пакета APK необходимо использовать jarsigner, то важно сначала подписать пакет APK, а затем запустить zipalign.

Предварительные требования

В этом руководстве будет рассматриваться использование apksigner из средств сборки пакета SDK для Android v24.0.3 или более поздней версии. Предполагается, что пакет APK уже собран.

Для приложений, созданных с помощью более ранней версии средств сборки пакета SDK для Android, следует использовать средство jarsigner, как описано в разделе Подписывание пакета APK с помощью jarsigner.

Создание закрытого хранилища ключей (keystore)

keystore — это база данных сертификатов безопасности, которая создается с помощью программы keytool из пакета SDK для Java. Хранилище ключей крайне важно для публикации приложения Xamarin.Android, так как Android не будет запускать приложения, не имеющие цифровой подписи.

Во время разработки для подписывания приложения Xamarin.Android использует хранилище ключей, что позволяет развернуть приложение непосредственно в эмуляторе на устройствах, настроенных для использования отлаживаемых приложений. Однако это хранилище ключей не распознается как допустимое для распространения приложений.

Поэтому для подписывания приложений необходимо создать и использовать закрытое хранилище ключей. Это действие выполняется только один раз, так как один и тот же ключ будет использоваться для публикации обновлений и для подписывания других приложений.

Очень важно обеспечить безопасность этого хранилища ключей. В случае его потери будет невозможно публиковать изменения для приложения в Google Play. Единственное решение проблемы, связанной с потерянным хранилищем ключей, заключается в создании нового хранилища ключей, повторном подписывании пакета APK новым ключом и отправке нового приложения. Старое приложение потребуется удалить из Google Play. Аналогично, в случае нарушения безопасности нового хранилища ключей или его публичного распространения в широкую доступность могут выйти неофициальные или вредоносные версии приложения.

Создание нового хранилища ключей

Для создания нового хранилища ключей требуется средство командной строки keytool из пакета SDK для Java. Ниже приведен пример использования keytool (замените именем файла хранилища ключей, а — именем ключа в хранилище ключей):

Чтобы получить список ключей, хранящихся в хранилище ключей, используйте его с параметром –: list

Оптимизация пакета APK

Перед подписыванием пакета APK с помощью apksigner сначала необходимо оптимизировать файл с помощью средства zipalign из пакета SDK для Android. zipalign выравнивает ресурсы в пакете APK по 4-байтовым границам. Благодаря выравниванию Android может быстро загружать ресурсы из пакета APK, повышая производительность приложения и потенциально сокращая использование памяти. Чтобы определить, прошел ли пакет APK оптимизацию, Xamarin.Android будет проводить проверку во время выполнения. Если пакет APK не оптимизирован, приложение не запустится.

Следующая команда использует подписанный пакет APK, а ее результатом будет подписанный, оптимизированный пакет APK helloworld.apk, готовый к распространению.

Подписывание пакета APK

Оптимизированный пакет APK необходимо подписать с использованием хранилища ключей. Для этого предназначено средство apksigner, находящееся в каталоге build-tools версии средств сборки пакета SDK. Например, если установлены средства сборки пакета SDK для Android v25.0.3, apksigner можно найти в следующем каталоге:

При выполнении этой команды при необходимости apksigner запросит пароль для хранилища ключей.

Дополнительные сведения об использовании apksigner см. в документации Google.

Согласно проблеме Google 62696222, средство apksigner «отсутствует» в пакете SDK для Android. Решением этой проблемы является установка средств сборки пакета SDK для Android v25.0.3 и использование этой версии apksigner.

Подписывание пакета APK с помощью jarsigner

Сведения в этом разделе применимы, если пакет APK необходимо подписать с помощью программы jarsigner. Для подписывания пакета APK разработчикам рекомендуется использование apksigner.

Эта методика предполагает подписывание APK-файла с помощью jarsigner из пакета SDK для Java. Средство jarsigner входит в состав пакета SDK для Java.

При использовании jarsigner важно сначала подписать пакет APK, а затем использовать средство zipalign.

How to Sign an Already Compiled Apk

I’ve decoded an APK with apktool (as the original source code was lost) so I could fix some issues with the layout xml files. I’ve then rebuilt it back up with apktool and when I tried to install it on my device (using adb: adb install appname.apk) it gave me this error:

the original apk however was signed by a keystore (on eclipse IDE), this one isn’t, how can I sign it properly with it’s original keystone file outside Eclipse!?

How to sign apk. Смотреть фото How to sign apk. Смотреть картинку How to sign apk. Картинка про How to sign apk. Фото How to sign apk

6 Answers 6

Trending sort

Trending sort is based off of the default sorting method — by highest score — but it boosts votes that have happened recently, helping to surface more up-to-date answers.

It falls back to sorting by highest score if no posts are trending.

Switch to Trending sort

create a key using

then sign the apk using :

Automated Process:

Use this tool (uses the new apksigner from Google):

Disclaimer: Im the developer 🙂

Manual Process:

Step 1: Generate Keystore (only once)

You need to generate a keystore once and use it to sign your unsigned apk. Use the keytool provided by the JDK found in %JAVA_HOME%/bin/

Step 2 or 4: Zipalign

zipalign which is a tool provided by the Android SDK found in e.g. %ANDROID_HOME%/sdk/build-tools/24.0.2/ is a mandatory optimization step if you want to upload the apk to the Play Store.

Note: when using the old jarsigner you need to zipalign AFTER signing. When using the new apksigner method you do it BEFORE signing (confusing, I know). Invoking zipalign before apksigner works fine because apksigner preserves APK alignment and compression (unlike jarsigner).

You can verify the alignment with

Step 3: Sign & Verify

Using build-tools 24.0.2 and older

Use jarsigner which, like the keytool, comes with the JDK distribution found in %JAVA_HOME%/bin/ and use it like so:

and can be verified with

Using build-tools 24.0.3 and newer

and can be verified with

How to sign apk. Смотреть фото How to sign apk. Смотреть картинку How to sign apk. Картинка про How to sign apk. Фото How to sign apk

fastest way is by signing with the debug keystore:

How to sign apk. Смотреть фото How to sign apk. Смотреть картинку How to sign apk. Картинка про How to sign apk. Фото How to sign apk

You use jarsigner to sign APK’s. You don’t have to sign with the original keystore, just generate a new one. Read up on the details: http://developer.android.com/guide/publishing/app-signing.html

For those of you who don’t want to create a bat file to edit for every project, or dont want to remember all the commands associated with the keytools and jarsigner programs and just want to get it done in one process use this program:

I built it because I was fed up with the lengthy process of having to type all the file locations every time.

This program can save your configuration so the next time you start it, you just need to hit Generate an it will handle it for you. That’s it.

No install required, it’s completely portable and saves its configurations in a CSV in the same folder.

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:

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:

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.

Key and certificate options

The following options specify the signer’s private key and certificate:

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:

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.

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:

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 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 and OpenJDK are trademarks or registered trademarks of Oracle and/or its affiliates.

Источники информации:

Добавить комментарий

Ваш адрес email не будет опубликован. Обязательные поля помечены *