Android studio signing config

Signing Your Applications

In this document

See also

Android requires that all apps be digitally signed with a certificate before they can be installed. Android uses this certificate to identify the author of an app, and the certificate does not need to be signed by a certificate authority. Android apps often use self-signed certificates. The app developer holds the certificate’s private key.

Signing Overview

You can sign an app in debug or release mode. You sign your app in debug mode during development and in release mode when you are ready to distribute your app. The Android SDK generates a certificate to sign apps in debug mode. To sign apps in release mode, you need to generate your own certificate.

Signing in Debug Mode

In debug mode, you sign your app with a debug certificate generated by the Android SDK tools. This certificate has a private key with a known password, so you can run and debug your app without typing the password every time you make a change to your project.

Android Studio signs your app in debug mode automatically when you run or debug your project from the IDE.

You can run and debug an app signed in debug mode on the emulator and on devices connected to your development manchine through USB, but you cannot distribute an app signed in debug mode.

By default, the debug configuration uses a debug keystore, with a known password and a default key with a known password. The debug keystore is located in $HOME/.android/debug.keystore, and is created if not present. The debug build type is set to use this debug SigningConfig automatically.

For more information about how to build and run apps in debug mode, see Building and Running.

Signing in Release Mode

In release mode, you sign your app with your own certificate:

  1. Create a keystore. A keystore is a binary file that contains a set of private keys. You must keep your keystore in a safe and secure place.
  2. Create a private key. A private key represents the entity to be identified with the app, such as a person or a company.

Add the signing configuration to the build file for the app module:

  • Invoke the assembleRelease build task from Android Studio.
  • The package in app/build/apk/app-release.apk is now signed with your release key.

    Note: Including the passwords for your release key and keystore inside the build file is not a good security practice. Alternatively, you can configure the build file to obtain these passwords from environment variables or have the build process prompt you for these passwords.

    To obtain these passwords from environment variables:

    To have the build process prompt you for these passwords if you are invoking the build from the command line:

    After you complete this process, you can distribute your app and publish it on Google Play.

    Warning: Keep your keystore and private key in a safe and secure place, and ensure that you have secure backups of them. If you publish an app to Google Play and then lose the key with which you signed your app, you will not be able to publish any updates to your app, since you must always sign all versions of your app with the same key.

    The rest of this document provides detailed instructions about how to generate a private key and sign your apps in release mode with Android Studio.

    Signing Android Wear Apps

    When publishing Android Wear apps, you package the wearable app inside of a handheld app, because users cannot browse and install apps directly on the wearable. Both apps must be signed. For more information on packaging and signing Android Wear apps, see Packaging Wearable Apps.

    Signing Your App in Android Studio

    To sign your app in release mode in Android Studio, follow these steps:

      On the menu bar, click Build >Generate Signed APK.

    On the Generate Signed APK Wizard window, click Create new to create a new keystore.

    If you already have a keystore, go to step 4.

    Читайте также:  Пишет нет памяти хотя память есть андроид

    On the New Key Store window, provide the required information as shown in figure 1.

    Your key should be valid for at least 25 years, so you can sign app updates with the same key through the lifespan of your app.

    Figure 1. Create a new keystore in Android Studio.

    On the Generate Signed APK Wizard window, select a keystore, a private key, and enter the passwords for both. Then click Next.

    Figure 2. Select a private key in Android Studio.

    On the next window, select a destination for the signed APK and click Finish.

    Figure 3. Generate a signed APK in Android Studio.

    Automatically Signing Your App

    In Android Studio, you can configure your project to sign your release APK automatically during the build process:

    1. On the project browser, right click on your app and select Open Module Settings.
    2. On the Project Structure window, select your app’s module under Modules.
    3. Click on the Signing tab.

    Select your keystore file, enter a name for this signing configuration (as you may create more than one), and enter the required information.

    Figure 4. Create a signing configuration in Android Studio.

    Under Signing Config, select the signing configuration you just created.

    Figure 5. Select a signing configuration in Android Studio.

    You can also specify your signing settings in Gradle configuration files. For more information, see Configuring Gradle Builds.

    Signing Considerations

    You should sign all of your apps with the same certificate throughout the expected lifespan of your applications. There are several reasons why you should do so:

    • App upgrade: When the system is installing an update to an app, it compares the certificate(s) in the new version with those in the existing version. The system allows the update if the certificates match. If you sign the new version with a different certificate, you must assign a different package name to the application—in this case, the user installs the new version as a completely new application.
    • App modularity: Android allows apps signed by the same certificate to run in the same process, if the applications so requests, so that the system treats them as a single application. In this way you can deploy your app in modules, and users can update each of the modules independently.
    • Code/data sharing through permissions: Android provides signature-based permissions enforcement, so that an app can expose functionality to another app that is signed with a specified certificate. By signing multiple apps with the same certificate and using signature-based permissions checks, your apps can share code and data in a secure manner.

    If you plan to support upgrades for an app, ensure that your key has a validity period that exceeds the expected lifespan of that app. A validity period of 25 years or more is recommended. When your key’s validity period expires, users will no longer be able to seamlessly upgrade to new versions of your application.

    If you plan to publish your apps on Google Play, the key you use to sign these apps must have a validity period ending after 22 October 2033. Google Play enforces this requirement to ensure that users can seamlessly upgrade apps when new versions are available.

    Securing Your Private Key

    Maintaining the security of your private key is of critical importance, both to you and to the user. If you allow someone to use your key, or if you leave your keystore and passwords in an unsecured location such that a third-party could find and use them, your authoring identity and the trust of the user are compromised.

    If a third party should manage to take your key without your knowledge or permission, that person could sign and distribute apps that maliciously replace your authentic apps or corrupt them. Such a person could also sign and distribute apps under your identity that attack other apps or the system itself, or corrupt or steal user data.

    Your private key is required for signing all future versions of your app. If you lose or misplace your key, you will not be able to publish updates to your existing appn. You cannot regenerate a previously generated key.

    Your reputation as a developer entity depends on your securing your private key properly, at all times, until the key is expired. Here are some tips for keeping your key secure:

    • Select strong passwords for the keystore and key.
    • Do not give or lend anyone your private key, and do not let unauthorized persons know your keystore and key passwords.
    • Keep the keystore file containing your private key in a safe, secure place.

    In general, if you follow common-sense precautions when generating, using, and storing your key, it will remain secure.

    Expiry of the Debug Certificate

    The self-signed certificate used to sign your application in debug mode has an expiration date of 365 days from its creation date. When the certificate expires, you will get a build error.

    To fix this problem, simply delete the debug.keystore file. The default storage location is in

    /.android/ on OS X and Linux, in C:\Documents and Settings\ \.android\ on Windows XP, and in C:\Users\ \.android\ on Windows Vista and Windows 7.

    The next time you build, the build tools will regenerate a new keystore and debug key.

    Note that, if your development machine is using a non-Gregorian locale, the build tools may erroneously generate an already-expired debug certificate, so that you get an error when trying to compile your application. For workaround information, see the troubleshooting topic I can’t compile my app because the build tools generated an expired debug certificate.

    Signing Your App Manually

    You do not need Android Studio to sign your app. You can sign your app from the command line using standard tools from the Android SDK and the JDK. To sign an app in release mode from the command line:

    Generate a private key using keytool . For example:

    This example prompts you for passwords for the keystore and key, and to provide the Distinguished Name fields for your key. It then generates the keystore as a file called my-release-key.keystore . The keystore contains a single key, valid for 10000 days. The alias is a name that you will use later when signing your app.

    Compile your app in release mode to obtain an unsigned APK.

    Sign your app with your private key using jarsigner :

    This example prompts you for passwords for the keystore and key. It then modifies the APK in-place to sign it. Note that you can sign an APK multiple times with different keys.

    Verify that your APK is signed. For example:

    Align the final APK package using zipalign .

    zipalign ensures that all uncompressed data starts with a particular byte alignment relative to the start of the file, which reduces the amount of RAM consumed by an app.

    Источник

    Android: создание динамических Product Flavors и Signing Configs

    При работе над Android-проектом, представляющий собой платформу для создания приложений для просмотра видео-контента, возникла необходимость динамического конфигурирования product flavors с выносом информации о signing configs во внешний файл. Подробности под катом.

    Исходные данные

    Имеется Android-проект, представляющий собой платформу для создания приложений для просмотра видео-контента. Кодовая база общая для всех приложений, различия заключаются в настройках параметров REST API и настройках внешнего вида приложения (баннеры, цвета, шрифты и т.д.). В проекте использованы три flavor dimension:

    1. market: «google» или «amazon». Т.к. приложения распространяются как в Google Play, так и в Amazon Marketplace, имеется необходимость разделять некоторый функционал в зависимости от места распространения. Например: Amazon запрещает использование In-App Purchases механизма от Google и требует реализацию своего механизма.
    2. endpoint: «pro» или «staging». Специфические конфигурации для production и staging версий.
    3. site: собственно dimension для конкретного приложения. Задается applicationId и signingConfig.

    Проблемы с которыми мы столкнулись

    При создании нового приложения необходимо было добавить Product Flavor:

    Также, необходимо было добавить соответствующий Signing Config:

    Проблемы:

    Вынос информации о сертификатах

    Первым шагом был вынос информации о сертификатах в отдельный json-файл. Для примера информация так-же хранится в plain-text, но ничего не мешает хранить файл в зашифрованном виде (мы используем GPG) и расшифровывать непосредственно во время сборки приложения. JSON-файл имеет следующую структуру:

    Секцию signingConfigs в build.gradle файле удаляем.

    Упрощение Product Flavors секции

    Для сокращения количества строк, необходимых для описания Product Flavor с dimension = «site», был создан массив с необходимой информацией для описания конкретного приложения, а все Product Flavors с dimension=»site» были удалены.
    Было:

    Динамическое создание Product Flavors

    Последним шагом оставалось динамически создавать product flavors и signing configs используя внешний JSON-файл с информацией о сертификатах из массива applicationDefinitions.

    Для добавления чтения из зашифрованного хранилища необходимо заменить секцию

    Источник

    Настройка подписывания кода Android в центре приложений

    Для пользователей Xamarin. Android процесс немного отличается. Дополнительные сведения см. в статье о подписывания кода Xamarin. Android .

    Подписывание приложения является обязательным для запуска приложения на реальных устройствах в процессе разработки или для распространения его с помощью программы бета-тестирования или Магазин Google Play. Без подписывания кода приложение может выполняться только в эмуляторе.

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

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

    Если хранилище ключей в настоящее время отсутствует, его можно создать в Android Studio. Инструкции по созданию хранилища ключей для подписывания пакетов apk можно найти в официальном руководством пользователя Android Studio.

    Настройка подписывания кода

    Центр приложений поддерживает три разных способа настройки подписывания кода для приложений Android. Для всех трех методов необходимо сначала открыть конфигурацию сборки и включить подписывание кода:

    1. Перейдите к своему приложению в центре приложений.
    2. Перейдите в раздел Сборка.
    3. Перейдите к ветви, которую необходимо настроить, выбрав ее из списка.
    4. либо используйте меню «Параметры» в правом верхнем углу, либо выберите команду » настроить «, если ваша ветвь еще не настроена для сборки.
    5. Включить сборки подписывания.
    6. Выберите Сохранить.

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

    Начиная с Android 11, обязательно использовать подписывающий APK (если используется API уровня 30), так как в нем будут заданы некоторые дополнительные схемы «APK Signature (схема подписи v2 теперь требуется»). Центр приложений теперь (с момента выпуска Dec 17, 2020) подписывает приложения Android с помощью подсистемы APK Sign, а не подписывающий JAR, который использовался ранее. В рамках этой функции, чтобы включить APK Signing в центре приложений, была реализована задача подписывания Android v3, а в требованиях для новой задачи подписывания требовалось изменить способ сохранения файла хранилища ключей, чтобы сохранить файл хранилища ключей в защищенном файле аздо (задача «сборка и выпуск Android»-Azure pipelines | Документация Майкрософт).

    Все конфигурации сборки с файлами хранилища ключей, отправленными до 17 декабря 2020, по-прежнему используют метод подписывания APK Signature версии 2 (jarsigner). Чтобы использовать поток подписи с подписью APK версии 3, пользователям нужно просто повторно отправить свои файлы хранилища ключей и сохранить конфигурацию ветви.

    Использование подключаемого модуля Android Gradle версии 4.1. x не полностью поддерживается. Чтобы использовать эту версию, необходимо добавить в файл следующий параметр gradle.properties :

    A. Сохранение всех элементов в конфигурации Gradle

    Сведения о подписи можно указать в build.gradle файле (уровне приложения) . Сведения о подписывании, а также все учетные данные и сведения о хранилище ключей будут отображаться в репозитории. Сначала добавьте все необходимые элементы в код и верните их в репозиторий. Затем в конфигурации сборки в центре приложений параметр Включить Мои параметры Gradle полностью настроен для обработки подписи автоматически.

    Б. Отправка содержимого в центр приложений

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

    Сборка может быть подписана только один раз. Убедитесь, что у вас нет конфликтов с конфигурациями подписывания в конфигурации Gradle для выбранного варианта сборки. Если в центре приложений и в файле Gradle есть параметры подписывания, сборка может быть подписана дважды, а это приводит к конфликтам.

    Настройте конфигурацию сборки в центре приложений следующим образом:

    1. Параметр отключить параметры Gradle полностью настроен для автоматической подписывания.
    2. Upload файл хранилища ключей для отправки файла хранилища ключей . Можно перетащить файл на поле или щелкнуть его и выбрать файл. Файлы хранилища ключей имеют расширение .keystore или .jks .
    3. Введите пароль хранилища ключей, псевдоним ключа и пароль ключа в соответствующих полях. Это те же значения, которые в противном случае вводятся в Android Studio при подписании сборки.

    В. Хранение сведений о подписываниях в репозитории с помощью переменных среды

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

    В приведенном выше коде защита значений системных свойств, внедренных в сборку, обеспечивает безопасность учетных данных для подписи — значения шифруются и доступны только агентам сборки во время сборки. Вы можете указать значения в центре приложений. Можно также жестко кодировать любое из значений и вернуть их в репозиторий. Чтобы использовать центр приложений для защиты значений:

    1. Перейдите к конфигурации сборки.
    2. Убедитесь, что флажок с именем Мои параметры Gradle полностью настроен для автоматической подписывания , он не установлен.
    3. Введите пароль хранилища ключей, псевдоним ключа и пароль ключа в соответствующих полях. Это те же значения, которые в противном случае вводятся в Android Studio при подписании сборки.

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

    Если вы используете signingConfig параметр внутри buildTypes раздела в build.gradle файле уровня приложения , вы можете столкнуться с ошибками подписи кода во время сборки центра приложений. это особенно важно для приложений, использующих React Native для Android версии 0,60.. x и выше.

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

    Источник

    Читайте также:  Android custom keyboard codes
    Оцените статью