Android sign with jks

Ручная подписка APK

Тут вам покажем несколько способов инструментов, при помощи которых можно подписывать приложения Android перед публикацией их в Google App Play.

Подписка APK средствами IDE Android Studio

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

Чтобы вручную подписать APK для выпуска в Android Studio, выполните следующие действия:

  1. Жмем Build > Generate Signed APK и откроется окно Generate Signed APK . (Как создать ключи подписи в Android Studio мы писали в прошлой статье)
  2. В окне Generate Signed APK Wizard выберите хранилище ключей, закрытый ключ и введите пароли для обоих. (Если вы только что создали хранилище ключей в предыдущем разделе, эти поля уже будут заполнены) Затем нажмите «Next»
  3. В следующем окне выберите пункт назначения для подписанных APK, выберите тип сборки (если применимо), выберите продукт (ы) и нажмите «Finish»

Когда процесс завершится, вы найдете свой подписанный APK в выбранной вами папке назначения. Теперь вы можете распространять подписанный APK через торговую площадку приложения, например, в Google Play Store, или использовать выбранный вами механизм распространения подписанного приложения конечным пользователям.

Чтобы пользователи могли успешно устанавливать обновления для вашего приложения, вам нужно будет подписать APK с тем же сертификатом на протяжении всего срока действия вашего приложения.

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

Есть сгенерированные ключи подписи или создаем?

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

Примечание: keytool находится в каталоге bin/ вашего JDK. Чтобы найти ваш JDK из Android Studio, выберите «File»> «Project Structure», а затем «SDK Location», и вы увидите местоположение JDK

В этом примере команды консоль еще запросит ввести пароли для хранилища ключей и ключа подписи и запросит заполнить поля Distinguished Name для вашего ключа. Затем он генерирует хранилище ключей в виде файла с именем my-release-key.jks, сохраняя его в текущем каталоге (вы можете перемещать его по своему усмотрению). Хранилище ключей содержит один ключ, действительный в течение 10 000 дней.

Теперь вы можете создать unsigned APK, т.е. построить конфигурацию release и подписать его вручную или вместо этого настроить Gradle для автоматического подписания APK.

Подписка APK средствами командной строки Android SDK

Инструмент apksigner, доступный в версии 24.0.3 и выше для Android SDK Build Tools, позволяет вам подписывать APK и подтверждать, что подпись APK будет проверена успешно на всех версиях платформы Android, поддерживаемых этими APK. В этом подразделе представлено краткое руководство по использованию инструмента и служит ссылкой для различных параметров командной строки, которые поддерживает инструмент

Примечание 1. если вы подписываете APK с помощью apksigner и вносите дальнейшие изменения в APK, подпись APK становится недействительной. Поэтому перед подписанием APK вы должны использовать такие инструменты, как zipalign.

Примечание 2. Чтобы использовать инструмент apksigner, вы должны иметь версию 24.0.3 или выше установленных инструментов Android SDK Build Tools. Вы можете обновить этот пакет с помощью диспетчера SDK.

Читайте также:  Темы для андроид космос

1). Открываем командную строку и перемещаемся в корневую директорию —из Android Studio, выбираем View > Tool Windows > Terminal. Затем вызываем команду assembleRelease :

Это создает APK под именем module_name-unsigned.apk в папке project_name/module_name/build/outputs/apk/. APK будет неподписанным(unsigned) и невыровненным(unaligned), который на данный момент — он не может быть установлен до тех пор, пока не будет подписан вашим секретным ключом.

2). Align the unsigned APK using zipalign:

zipalign гарантирует, что все несжатые данные начинаются с конкретного выравнивания байтов относительно начала файла, что может уменьшить объем оперативной памяти, потребляемой приложением.

3). Подписываем APK своим личным ключом с помощью apksigner:

В этом примере выводится подписанный APK на my-app-release.apk после его подписания с закрытым ключом и сертификатом, который хранится в одном файле хранилища ключей: my-release-key.jks.

Инструмент apksigner поддерживает другие параметры подписки, включая подписание файла APK с использованием отдельного закрытого ключа и файлов сертификатов и подписку APK с использованием нескольких подписчиков. Для получения дополнительной информации см. ссылку apksigner.

4). Убеждаемся, что ваш APK подписан:

Пример подписки средствами Android SDK

Если вышеописанное вызывает трудности, то давайте сделаем некоторый простой пример генерации ключа командой keytool, выполнения операции zipalign и подписи командой apksigner.

Сначала строим релиз средствами Cordova и Android SDK

Команда keytool генерации ключа в консоли:

Операция zipalign в консоли:

Обратите внимание, что zipalign мы выполняем по прямому пути версии приложения, которая соответствует версии нашего разрабатываемого приложения.

Операция подписи apksigner:

Обратите внимание, что apksigner мы выполняем по прямому пути версии приложения и указываем путь к сгенерированному ключу, которая соответствует версии нашего разрабатываемого приложения. Далее, после нажатия Enter, консоль запросит поочередно запросить пароль от хранилища ключей и от самого ключа.

Подписка APK средствами командной строки JDK

Выше мы уже знакомились с инструментом keytool для создания хранилища ключей и самих ключей подписи в составе JDK, а в данной секции описано то, как средствами JDK подписывать этим ключом приложение и для этого есть специальный инструмент в составе JDK в той же папке, что и keytool — jarsigner.

Команда подписи с ее параметрами записывается так

Имена параметров нам знакомы по keytool:

  • хранилище (keystore),
  • пароль (storepass) к нему
  • пароль (keypass) к ключу.
  • А последние два параметра – это имя APK-файла, который вы хотите подписать и алиас ключа из указанного хранилища, который вы хотите использовать для подписи.

После данной команды приложение будет подписано и будет готово к установке на устройства или можно распространять через Google App Play.

Другие инструменты подписи

Пожалуй, сюда можно добавить такие инструменты, как:

  • apk-signer — простой инструмент командной строки для подписи apk
  • APK Signing Tool — этот инструмент с оконным интерфейсом позволяет вам подписать APK с вашим хранилищем ключей. Вы можете переопределить хранилище демо-версий и использовать свое собственное хранилище ключей перед загрузкой приложения в Google Play.
  • APK Signer — инструмент с оконным интерфейсом упрощает создание файла хранилища ключей.

Источник

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 Determines whether apksigner signs the given APK package using the traditional, JAR-based signing scheme. By default, the tool uses the values of —min-sdk-version and —max-sdk-version to decide when to apply this signature scheme. —v2-signing-enabled Determines whether apksigner signs the given APK package using the APK Signature Scheme v2. By default, the tool uses the values of —min-sdk-version and —max-sdk-version to decide when to apply this signature scheme. —v3-signing-enabled Determines whether apksigner signs the given APK package using the APK Signature Scheme v3. By default, the tool uses the values of —min-sdk-version and —max-sdk-version to decide when to apply this signature scheme. —v4-signing-enabled Determines whether apksigner signs the given APK package using the APK Signature Scheme v4. This scheme produces a signature in an separate file ( apk-name .apk.idsig ). If true and the APK is not signed, then a v2 or v3 signature is generated based on the values of —min-sdk-version and —max-sdk-version . The command then produces the .idsig file based on the content of the signed APK. Use only to generate only the v4 signature without modifying the APK and any signatures it had before the invocation; only fails if the APK doesn’t have a v2 or v3 signature already, or if the signature used a different key than the one provided for the current invocation. By default, the tool uses the values of —min-sdk-version and —max-sdk-version to decide when to apply this signature scheme. -v , —verbose Use the verbose output mode.

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.

Читайте также:  Автомобильный интерфейс для android

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.

  • env: – Password is stored in the given environment variable.
  • file: – Password is stored as a single line in the given file.
  • stdin – Password is provided as a single line in the standard input stream. This is the default behavior for —ks-pass .
  • 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.

  • env: – Password is stored in the given environment variable.
  • file: – Password is stored as a single line in the given file.
  • stdin – Password is provided as a single line in the standard input stream. This is the default behavior for —key-pass .
  • 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.

    Источник

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