Signing an .apk file using the jarsigner utility. How to sign an APK game or application on Android correctly How to change the signature of an android application

Since I googled the question myself how to sign apk file?", I know that it is not so easy to find a really working and understandable instruction in everything. That is why I decided to write material myself on how to properly sign your program or game on Android.

As is now known digital signature, your creation cannot be placed on the Market, and this is already serious. I noticed a lot of young Android developers, so to speak, beginners completely forget to sign their application and try to do something with it later and everyone wonders why they don’t it is possible to perform this or that action with their APK file.

So, let's not drag it out and start right away with how you can sign your apk file and how to actually use it to achieve the desired result.

This method is the most correct of all listed, so we will describe it in this material. We will make our own keys with our data and certificates and use them to sign the application you created.

For work we need: OpenSSL and SignApk.

First, let's make a certificate and a signing key. Install OpenSSL. During installation, the installer will prompt you to copy the components to the Windows folder, select the Bin folder, which will be the place where you install the entire OpenSSL.

Now open on behalf of the system administrator (this is very important!) the command line. Then, on the command line, go to the bin folder, which is located in the folder where you installed OpenSSL (For example, C:\OpenSSL\bin\ or C:\Program Files\OpenSSL\bin\). If you don't know, moving to another folder is done with the command cd. That is, in order to go to the desired folder, you should run the following command:

cd C:\OpenSSL\bin\

Once you're in the Bin folder, you can proceed directly to creating a certificate and key.

Step 1(We perform key generation with a length of 1024 bits)

Run the command:

openssl genrsa -out key.pem 1024

Step 2(Based on the key, we create a certificate request)

Run the command:

openssl req -new -key key.pem -out request.pem

At this stage, you will need to enter your data, which will identify you in the certificate.

Step 3 (Generate a private key from a certificate)

Run the command:

openssl x509 -req -days 9999 -in request.pem -signkey key.pem -out certificate.pem

Step 4(Perform public key generation)

Run the command:

openssl pkcs8 -topk8 -outform DER -in key.pem -inform PEM -out key.pk8 -nocrypt

At this stage, the creation of the files we need to sign your games and applications is finished. using the generated key and certificate, you can sign as many games and applications on Android as you like.

And now actually, let's start signing the application. Unpack the archive from SingApk downloaded from the link above. Move from the Bin folder where we created the certificate and key 2 files: certificate.pem and key.pk8 to the folder where you unpacked SingApk. Windows should display a file replacement dialog - replace.

Now, in order to sign the apk file with a unique digital signature that you made yourself, simply drag your apk file to sign_APK.bat. In order not to drag the file from one window to another (this is not convenient), move your apk file to the folder with SingApk. After execution, a file will appear in the folder with SingApk apk_signed.apk, which will be your signed application or game.

With the app signing feature in Google Play Google can manage your app's signing key, and protect this key and use it to sign your APKs for distribution. This storage method will protect you in case the key is lost or tampered with.

Important! To use Android App Bundles (the recommended format for publishing apps), you must enroll in the Google Play App Signing Program before uploading the App Bundle to the Play Console.

Account holders and users with global production management permissions who have accepted the Terms of Use can register. You can only register one app at a time in the Google Play App Signing Program.

Work principles

When you use the app signing feature on Google Play, your keys are stored in the same infrastructure as Google keys and protected by a special key management service. Detailed information about Google's technical infrastructure can be found in the Google Cloud security documentation.

Android apps are signed with a private key. Associated with each such key is a public certificate that devices and services can use to verify the security of applications and their updates. Only those updates are installed on devices whose signature matches the signature installed application. If you let Google manage your app signing key, the process is more secure.

Note. It is optional to use the app signing feature in Google Play. You can upload APKs and manage your own keys without using App Bundles. However, if you lose access to the keystore or it gets compromised, you won't be able to update your app and will have to republish it with a different package name.

Descriptions of keys, objects and tools
Terms Description
Application signing key

The key used by Google Play to sign APK files delivered to the user's device. When you sign up for the app signing program on Google Play, you can upload an existing signing key or let Google generate a new one.

Download key

There are two ways to generate an upload key:

  • Use the application signing key. If you allowed Google to generate an app signing key when you signed up for the program, the upload key will be the key you used to sign the first release of the app.
  • Use a separate upload key. If you submitted your own app signing key when you signed up for the program, you can generate a new upload key for security. If you don't want to do this, use the app signing key as your download key to sign new releases.
Certificate (.der or .pem)

A certificate that contains the public key and additional information about its owner. The public key certificate lets anyone know who signed the App Bundle or APK file. This certificate can be shared because it does not include a private key.

To register keys with API providers, you can download the public certificate for the application signing key on the page Application signing in the Play Console. The public key certificate can be shared with everyone because it does not include the private key.

Certificate fingerprint

A short and unique identifier for the certificate. The thumbprint, along with the package name, is often requested by API providers to provide access to their services.

The MD5, SHA-1, and SHA-256 fingerprints of the application upload and sign certificates can be found at Application signing in the Play Console. You may also receive a different type of digital fingerprint. To do this, download the original certificate in DER format on the same page.

Java keystore (.jks or .keystore) Storage of security certificates and private keys.
PEPK Tool

A tool to export private keys from Java storage and encrypt them for submission to Google Play.

Once you've provided Google with your app signing key, choose to export and upload your own key (and its public certificate if necessary), then follow the instructions to download and use the tool. You can also download, view and use the open source PEPK tool.

Application signing process

You can upload APK files signed with the original app signing key before or after signing the app on Google Play.

If you upgrade to Android App Bundles, you can test them in test versions and use existing APKs in production versions. Here's how it works:

  1. You sign an App Bundle or APK and upload it to the Play Console.
  2. The app signing process depends on what you're downloading.
    • App Bundle. Google optimizes the APKs in the App Bundle and then signs them with the App Signing Key.
    • APK file signed with the upload key. Google verifies your signature, removes it, and re-signs APKs with the app signing key.
    • An APK file signed with an application signing key. Google verifies the signature.
  3. Google delivers signed APK files to users.

How to enroll in the Google Play App Signing Program

New Applications

Step 1: Create an upload key

  1. Create an upload key following the instructions.
  2. Sign the new APK file with an upload key.

Step 2: Prepare the release

  1. following the instructions.
  2. Once you've selected a version type, configure your app signing options under "Let Google secure and manage your app signing key."
  3. If you click Proceed, the generated key will become the upload key that will be used to sign future releases. You can also choose from the following Advanced settings:
    • Use one key for different applications in the developer account (option 2).
    • Upload the signing key of an existing application (option 2, 3 and 4) by choosing the export and upload method that suits you best. After uploading the application signing key and its public certificate, you can either use the application signing key as the application signing key.

Note. To continue, you must accept the Terms of Use and enroll in the App Signing Program.

Step 3: Register your app signing key with API providers

If your application uses an API, then in order to authenticate, you will most likely need to register a key certificate with which Google signs your application. To find a certificate:

  1. Sign in to the Play Console.
  2. Select an application.
  3. From the menu on the left, select Release Management > Application Signatures.
    • If the API provider requires a different type of fingerprint, you can download the original certificate in DER format and convert it as needed using the appropriate tools.
Published Applications

Step 1: Sign up for the Google Play App Signing Program

  1. Sign in to the Play Console.
  2. Select an application.
  3. From the menu on the left, select Release Management > Application Signatures.
  4. If necessary, read the Terms of Use and click To accept.

Step 2 Submit the original key to Google and generate an upload key

  1. Find the original app signing key.
  2. Sign in to the Play Console.
  3. Select an application.
  4. From the menu on the left, select Release Management > Application Signatures.
  5. Upload your existing app signing key in the way that best suits your release process.
  1. and upload the certificate on Google Play.
    • You can also use the application signing key as the upload key.
  2. Copy the thumbprints (MD5, SHA-1, and SHA-256) of the application signing certificate.
    • For testing purposes, you may need to register an upload key certificate with the API provider using the certificate's thumbprint and application signing key.

Step 4: Sign your app's next update with an upload key

App updates that are released must be signed with a download key.

How to generate an upload key and update keystores

You can generate an upload key when you sign up for the app signing program on Google Play, or you can generate one later in the section Release Management > Application Signatures.

To create an upload key, follow these steps:

  1. Follow the instructions on the Android Developers site. Keep the key in a safe place.
  2. Export the boot key certificate in PEM format. Replace the following arguments with underscores:
    • $ keytool -export -rfc -keystore upload-keystore.jks -alias upload -file upload_certificate.pem
  3. When prompted during the release process, upload the certificate to register it with Google.

If you are using an upload key:

  • The upload key is only registered with Google to authenticate the identity of the app creator.
  • Your signature is removed from all uploaded APKs before they reach users.
Restrictions
  • The upload key must use RSA encryption and must be at least 2048 bits in size.
  • DSA and EC keys and RSA keys smaller than 2048 bits are not supported.
Updating keystores

Once you've created your boot key, check and update the following locations as needed:

  • local system;
  • secure local server (with various access control lists);
  • cloud system (with various access control lists);
  • special services for key management;
  • Git repositories.

How to update the signing key for new app installations

In some cases, you can request an update of the app's signing key. The new key will be used to sign new installs and updates to the application, while the legacy key will be used to update signed versions that users have already installed.

The signing key can only be updated once per application. In the unlikely event that you use the same signing key for multiple applications to run in the same process, the key cannot be updated.

You should request an update of the application signing key in the following cases:

  • You need a more cryptographically strong key.
  • The app signing key has been compromised.

Note. The request to update the app signing key on the Play Console is not related to key replacement in Android P and later. This key replacement is currently not supported by Google Play.

Important notes about updating keys

Before requesting a key update, it is important to understand what changes this will entail.

  • If you're using the same signing key for multiple apps to use the same code or data, you'll need to update the apps to recognize both the new and legacy keys.
  • If your app uses an API, be sure to register the certificates for the new and legacy app signing keys with the API provider before updating it. Certificates are available on the page Application signing Play Console.
  • If many users of your app install updates via file-sharing networks, they will only be able to install updates signed with the same key as the app installed on their devices. If applications cannot be updated because installed version signed with a different key, users can uninstall and reinstall it to receive updates.
Request a key update for new installations. To do this, follow these steps:
  1. Sign in to the Play Console.
  2. Select an application.
  3. From the menu on the left, select Release Management > Application Signatures.
  4. In the "Update signing key for new app installs" card, select Request key update.
  5. Choose what to do with the device.
    • Depending on the option you choose, you may have to contact support to complete your request.
  6. Let Google Play generate a new app signing key (recommended) or download one.
    • After updating the app signing key, if the key was the same as the upload key, you can continue to use the old app signing key as the upload key or create a new one.
  • If you have also published your app outside of Google Play, or intend to do so, you can generate a pre-shared app signing key and upload it to Google when you sign up for the Google Play App Signing Program.
  • To protect your account, turn on two-step verification for all accounts that have access to the Play Console.
  • Once an App Bundle is published in a test or production version, you can open the App Bundle Browser and download the ZIP archive containing all the APKs for a specific device. These APKs are already signed with the app signing key. You can install them on the device from a ZIP archive using the utility command line bundletool.
  • For greater security, generate a new upload key that is different from the app signing key.
  • If you want to test an APK signed with an upload key, register the key with a service or API that uses the app's signature for authentication (such as the Google Maps API or the Facebook SDK).
  • If you are using the Google APIs, you can register the upload certificate in the Google Cloud Console .

What to do if the key is lost or hacked

If you have lost access to your private upload key or it has been hacked and ask your account owner. When contacting support, the account owner must attach the upload_certificate.pem file.

When the support team registers a new upload key, you will receive an email and then you can update the keystores and register the key with the API providers.

Important! Resetting the upload key does not affect the app signing key that Google Play uses to sign APK files before they are sent to users.

Was this information helpful?

How can this article be improved?

Sometimes some applications on Android do not suit the user for some reason. An example is annoying ads. And it happens that way - everyone is good at the program, but only the translation in it is either crooked, or completely absent. Or, for example, the program is trial, but there is no way to get the full version. How to change the situation?

Introduction

In this article, we will talk about how to disassemble an APK with an application, look at its internal structure, disassemble and decompile the bytecode, and also try to make several changes to applications that can bring us this or that benefit.

To do all this yourself, you will need at least a basic knowledge of the Java language, in which Android applications are written, and the XML language, which is used everywhere in Android - from describing the application itself and its access rights to storing strings that will be displayed on the screen. You will also need the ability to handle specialized console software.

So, what is the APK package in which absolutely all software for Android is distributed?

Application decompilation

In the article, we only worked with disassembled application code, however, if you make more serious changes to large applications, it will be much more difficult to understand the smali code. Fortunately, we can decompile the dex code into Java code, which, although not original and not compilable back, is much easier to read and understand the logic of the application. To do this, we need two tools:

  • dex2jar - translator of Dalvik bytecode to JVM bytecode, based on which we can get Java code;
  • jd-gui is a decompiler itself that allows you to get readable Java code from JVM bytecode. Alternatively, you can use Jad (www.varanecas.com/jad); although it is quite old, in some cases it generates more readable code than Jd-gui.

They should be used like this. First, we launch dex2jar, specifying the path to the apk package as an argument:

%dex2jar.sh mail.apk

As a result, the mail.jar Java package will appear in the current directory, which can already be opened in jd-gui to view the Java code.

Arranging APK packages and getting them

An Android application package is essentially a regular ZIP file that does not require any special tools to view the contents and unpack. It is enough to have an archiver - 7zip for Windows or console unzip in Linux. But that's about the wrapper. What's inside? Inside, we generally have the following structure:

  • META-INF/- contains a digital certificate of the application, certifying its creator, and checksums of the package files;
  • res/ - various resources that the application uses in its work, such as images, a declarative description of the interface, and other data;
  • AndroidManifest.xml- description of the application. This includes, for example, the list of required permissions, the required version of Android, and the required screen resolution;
  • classes.dex- compiled application bytecode for the Dalvik virtual machine;
  • resources.arsc- also resources, but of a different kind - in particular, strings (yes, this file can be used for Russification!).

The listed files and directories are, if not in all, then, perhaps, in the vast majority of APKs. However, there are a few more less common files/directories worth mentioning:

  • assets- analogue of resources. The main difference is that to access a resource, you need to know its identifier, while the list of assets can be obtained dynamically using the AssetManager.list() method in the application code;
  • lib- native Linux libraries written with the help of NDK (Native Development Kit).

This directory is used by game manufacturers to put their game engine written in C/C++ there, as well as by creators of high-performance applications (for example, Google Chrome). Understood the device. But how to get the package file of the application of interest? Since it is not possible to get APK files from the device without rooting (they are in the / data / app directory), and rooting is not always advisable, there are at least three ways to get the application file to the computer:

  • APK Downloader extension for Chrome;
  • Real APK Leecher app;
  • various file hosting and warezniki.

Which one to use is a matter of taste; we prefer to use separate applications, so we will describe the use of Real APK Leecher, especially since it is written in Java and, accordingly, it will work even in Windows, even in nix.

After starting the program, you need to fill in three fields: Email, Password and Device ID - and select a language. The first two are the e-mail and password of your Google account that you use on the device. The third is the device ID, and you can get it by dialing the code on the dialer # #8255## and then finding the line Device ID. When filling out, you need to enter only the ID without the android- prefix.

After filling in and saving, the message “Error while connecting to server” often pops up. It has nothing to do with Google Play, so feel free to ignore it and look for packages that interest you.

Review and modification

Let's say you found a package you are interested in, downloaded it, unpacked it ... and when you tried to view some XML file, you were surprised to find that the file is not a text file. How to decompile it and how to work with packages in general? Is it really necessary to install the SDK? No, you don't need to install the SDK. In fact, for all the steps to unpack, modify and package APK packages, the following tools are needed:

  • ZIP archiver for unpacking and packing;
  • smali- assembler/disassembler of Dalvik virtual machine bytecode (code.google.com/p/smali);
  • aapt- a tool for packing resources (by default, resources are stored in binary form to optimize application performance). Included with the Android SDK, but can be obtained separately;
  • Signer- a tool for digitally signing a modified package (bit.ly/Rmrv4M).

You can use all these tools separately, but this is inconvenient, so it is better to use higher-level software built on their basis. If you're on Linux or Mac OS X, there's a tool called apktool . It allows you to unpack resources into their original form (including binary XML and arsc files), rebuild the package with modified resources, but it does not know how to sign packages, so you will have to run the signer utility manually. Despite the fact that the utility is written in Java, its installation is rather non-standard. First you need to get the jar file itself:

$ cd /tmp $ wget http://bit.ly/WC3OCz $ tar -xjf apktool1.5.1.tar.bz2

$ wget http://bit.ly/WRjEc7 $ tar -xjf apktool-install-linux-r05-ibot.tar.bz2

$ mv apktool.jar ~/bin $ mv apktool-install-linux-r05-ibot/* ~/bin $ export PATH=~/bin:$PATH

If you work on Windows, then there is an excellent tool for it called Virtual Ten Studio , which also accumulates all these tools (including apktool itself), but instead of a CLI interface, it provides the user with an intuitive graphical interface with which to perform operations for unpacking, disassembling and decompiling in a few clicks. This tool is Donation-ware, that is, windows sometimes appear with a proposal to obtain a license, but this, in the end, can be tolerated. It makes no sense to describe it, because you can understand the interface in a few minutes. But apktool, due to its console nature, should be discussed in more detail.


Consider apktool options. In short, there are three main commands: d (decode), b (build) and if (install framework). If everything is clear with the first two commands, then what does the third one, the conditional operator, do? It unpacks the specified UI framework, which is needed when you dissect a system package.

Consider the most interesting options of the first command:

  • -s- do not disassemble dex files;
  • -r- do not unpack resources;
  • -b- do not insert debugging information into the results of disassembling the dex file;
  • --frame-path- use the specified UI framework instead of the built-in apktool. Now consider a couple of options for the b command:
  • -f- forced assembly without checking changes;
  • -a- specify the path to aapt (the tool for building the APK archive) if for some reason you want to use it from another source.

Using apktool is very simple, all you need to do is specify one of the commands and the path to the APK, for example:

$ apktool d mail.apk

After that, all the extracted and disassembled package files will appear in the mail directory.

Preparation. Disable ads

Theory is, of course, good, but why is it needed if we do not know what to do with the unpacked package? Let's try to apply the theory for our own benefit, namely, we modify some software so that it does not show us ads. For example, let it be Virtual Torch - a virtual torch. For us, this software is perfect, because it is full of annoying ads and is simple enough not to get lost in the wilds of code.


So, using one of the above methods, download the application from the market. If you decide to use Virtuous Ten Studio, just open the APK file in the application and unpack it, for which create a project (File -> New project), then in context menu project, select Import File. If your choice fell on apktool, then it is enough to execute one command:

$ apktool d com.kauf.particle.virtualtorch.apk

After that, a file tree will appear in the com.kauf.particle.virtualtorch directory, similar to the one described in the previous section, but with an additional smali directory instead of dex files and an apktool.yml file. The first one contains the disassembled code of the application's executable dex file, the second one contains the service information needed by apktool to assemble the package back.

The first place we need to look is, of course, AndroidManifest.xml. And here we immediately meet the following line:

It is easy to guess that she is responsible for granting the application permissions to use the Internet connection. In fact, if we just want to get rid of ads, it will most likely be enough for us to ban the application from the Internet. Let's try to do it. Delete the specified line and try to compile the software using apktool:

$ apktool b com.kauf.particle.virtualtorch

The resulting APK file will appear in the com.kauf.particle.virtualtorch/build/ directory. However, it cannot be installed because it does not have a digital signature and file checksums (it simply does not have a META-INF/ directory). We have to sign the package with the apk-signer utility. Launched. The interface consists of two tabs - on the first (Key Generator) we create keys, on the second (APK Signer) we sign. To create our private key, fill in the following fields:

  • Target File- keystore output file; it usually stores one pair of keys;
  • Password and Confirm- password for storage;
  • Alias- name of the key in the repository;
  • Alias ​​password and Confirm- secret key password;
  • Validity- Validity period (in years). The default value is optimal.

The remaining fields, in general, are optional - but you must fill in at least one.


WARNING

To sign an application with apk-signer, you must install the Android SDK and specify the full path to it in the application settings.

All information is provided for informational purposes only. Neither the editors nor the author are responsible for any possible harm caused by the materials of this article.

Now you can sign the APK with this key. On the APK Signer tab, select the newly generated file, enter the password, key alias and password for it, then find the APK file and boldly click the "Sign" button. If everything goes well, the package will be signed.

INFO

Since we signed the package with our own key, it will conflict with the original application, which means that when we try to update the software through the market, we will get an error.

Only third-party software needs a digital signature, so if you are modifying system applications that are installed by copying them to the /system/app/ directory, then you do not need to sign them.

After that, we drop the package on the smartphone, install and run. Voila, the ad is gone! Instead, however, a message appeared that we do not have the Internet or do not have the appropriate permissions. In theory, this could be enough, but the message looks annoying, and, to be honest, we just got lucky with a stupid application. A well-written software will most likely clarify its credentials or check for an Internet connection and otherwise simply refuse to start. How to be in this case? Of course, edit the code.

Typically, application authors create special classes for displaying advertisements and call methods of these classes during the launch of the application or one of its "activities" (in simple terms, application screens). Let's try to find these classes. We go to the smali directory, then com (in org there is only the open graphic library cocos2d), then kauf (exactly there, because this is the name of the developer and all his code is there) - and here it is, the marketing directory. Inside we find a bunch of files with the smali extension. These are classes, and the most notable of them is the Ad.smali class, by the name of which it is easy to guess that it displays ads.

We could change the logic of its work, but it would be much easier to stupidly remove calls to any of its methods from the application itself. Therefore, we exit the marketing directory and go to the neighboring particle directory, and then to virtualtorch. The MainActivity.smali file deserves special attention here. This is a standard Android class that is generated by the Android SDK and set as the entry point to the application (analogous to the main function in C). Open the file for editing.

Inside is the smali code (local assembler). It is rather confusing and difficult to read due to its low-level nature, so we will not study it, but simply find all mentions of the Ad class in the code and comment them out. We drive in the string "Ad" in the search and get to line 25:

Field private ad:Lcom/kauf/marketing/Ad;

Here, a field ad is created to store an object of class Ad. We comment by setting the ### sign in front of the line. We continue the search. Line 423:

New-instance v3, Lcom/kauf/marketing/Ad;

This is where the object is created. We comment. We continue the search and find in lines 433, 435, 466, 468, 738, 740, 800 and 802 calls to the methods of the Ad class. We comment. Look like that's it. We save. Now the package needs to be assembled back and checked for its performance and the presence of advertising. For the purity of the experiment, we return the line removed from AndroidManifest.xml, collect the package, sign it and install it.

Our guinea pig. Visible advertising

Op-pa! Advertising disappeared only while the application was running, but remained in the main menu, which we see when we launch the software. So, wait, but the entry point is the MainActivity class, and the advertisement disappeared while the application was running, but remained in the main menu, so the entry point is different? To reveal the true entry point, we reopen the AndroidManifest.xml file. And yes, it contains the following lines:

They tell us (and more importantly, the android) that the activity named Start should be launched in response to the generation of the android.intent.action.MAIN intent (event) from the android.intent.category.LAUNCHER category. This event is generated when you tap on the application icon in the launcher, so it defines the entry point, namely the Start class. Most likely, the programmer first wrote an application without a main menu, the entry point to which was the standard MainActivity class, and then added a new window (activity) containing a menu and described in the Start class, and manually made it an entry point.

We open the file Start.smali and again look for the line "Ad", we find in lines 153 and 155 the mention of the FirstAd class. It is also in the source code and, judging by the name, it is responsible for displaying ads on the main screen. We look further, there is a creation of an instance of the FirstAd class and an intent, according to the context related to this instance, and then the label cond_10, the conditional transition to which is carried out exactly before creating an instance of the class:

If-ne p1, v0, :cond_10 .line 74 new-instance v0, Landroid/content/Intent; ... :cond_10

Most likely, the program somehow randomly calculates whether it is necessary to show ads on the main screen, and if not, jumps directly to cond_10. Ok, let's simplify her task and replace the conditional transition with an unconditional one:

#if-ne p1, v0, :cond_10 goto:cond_10

There are no more mentions of FirstAd in the code, so we close the file and re-assemble our virtual torch using apktool. Copy to smartphone, install, run. Voila, all ads are gone, congratulations to all of us.

Results

This article is just a brief introduction to the methods of opening and modifying Android applications. Many issues remained behind the scenes, such as removing protection, parsing obfuscated code, translating and replacing application resources, as well as modifying applications written with using android NDK. However, having basic knowledge, understanding all this is only a matter of time.

Post Views: 5 618

android studio provides ample opportunities both for developing applications and for increasing automation and comfort when programming.

If you are using the build system gradle to create your own applications, you can also set up a few options for creating signatures for your applications.

You probably don't want to publish your signing keys, passwords, and usernames to a public (or even private) repository. Therefore, you can define the key, password, and username as properties in a separate file.

Before you start signing the application, you need to create a new property in the gradle.properties file. Let's call it keys.repo and, as a value, specify the path to the folder where the key store and the file with properties will subsequently be located (for example, C:/Users/UserName/.signing).

Keys.repo=C:/Users/UserName/.signing

Then you need to create this folder or, if you specified an existing one, open it. It needs to create a file YourProjectName.properties, inside which the path to the key store, key alias and password will be written as properties in the following form.

RELEASE_STORE_FILE=/YourProjectName/KeyStoreName.jks RELEASE_STORE_PASS=****** RELEASE_ALIAS=KeyAlias ​​RELEASE_KEY_PASS=******

How to create a keystore?

If you don't have a keystore, you can easily create one using Android Studio. To do this, select the menu item Build -> Generate Signed APK.

In the window that appears, click Create new... As a result, a window will open in which you can specify where the keystore will be located (for this lesson, it is better to immediately select the path that you specified in YourProjectName.properties in property RELEASE_STORE_FILE), as well as data about the key.

Then you need to create a folder YourProjectName and transfer the desired keystore file there.

Now you can proceed directly to the signing process. To do this, in your project you need to open the file build.gradle(located in the app folder). Inside it in the block android you need to add the following code.

SigningConfigs ( debug ( /* no change here */ ) release ( if (project.hasProperty("Keys.repo")) ( def projectPropsFile = file(project.property("Keys.repo") + "/YourProjectName.properties ") if (projectPropsFile.exists()) ( Properties props = new Properties() props.load(new FileInputStream(projectPropsFile)) storeFile file(file(project.property("Keys.repo") + props["RELEASE_STORE_FILE"] )) storePassword props["RELEASE_STORE_PASS"] keyAlias ​​props["RELEASE_ALIAS"] keyPassword props["RELEASE_KEY_PASS"] ) ) else ( println "===================== =================================" println " - Please configure release-compilation environment - e.g. in ~/. signing directory" println "=========================================== ==========" ) ) )

What are the signature schemes?

There are two schemes for obtaining an APK signature: v1 JAR and v2 Full APK.

In the first case, sign JAR-file, which is the traditional way of signing. The v1 signature does not protect some parts of the APK, such as the ZIP metadata. The APK verifier has to handle a lot of untrusted (not yet verified) data structures and then discard the data that is not signed, leaving a lot of room for attack. In addition, the APK verifier has to decompress all compressed records, which wastes a lot of time and memory. To address these issues, a second schema v2 Full APK was developed.

Schema v2 was introduced in Android 7.0 Nougat (API 25) and works since version Android Studio 2.2 and Android Gradle plugin 2.2. This scheme provides faster application installation and good protection against unauthorized changes to the APK. APK content is hashed and signed, then received APK signature block inserted into the APK.

During validation, the v2 schema treats the APK as a blob and performs signature verification on the entire file. Any modification to the APK, including modifications to the ZIP metadata, invalidates the signature. This form of verification is much faster and allows more unauthorized modifications to be detected.

The new format is backwards compatible, so APKs signed with the new scheme can be installed on older devices (which will simply ignore the new signature) as long as those APKs are also signed with the v1 scheme.

Signing uses both schemes by default so that applications can be installed on any device. However, if necessary, you can disable v1 or v2 signing. To do this, in the above code in the block release just add the following lines.

V1SigningEnabled false

V2SigningEnabled false

It is also important to note that you must sign with the v1 scheme before signing with the v2 scheme, because the APK will not pass v2 if it is signed with additional certificates after it has been signed with the v2 scheme.

After the code is added, indicate this code in the block buildTypes inside release. For example:

BuildTypes ( release ( minifyEnabled true shrinkResources true proguardFiles getDefaultProguardFile("proguard-android.txt"), "proguard-rules.pro" signingConfig signingConfigs.release ) )

Now you can safely in the menu item Build to choose Build APK, having previously changed the assembly type from debug on the release. As you can see, this method is convenient in that it is automatic, it only needs to be configured once and your keystores can be safe.

So, you've been working for many days (and maybe nights), and now your first hybrid mobile application is ready. It is quite stable, most of the critical bugs are closed. There are small ones left, but remembering that perfectionism is evil, you make a strong-willed decision to publish the application.

A prerequisite for this is the presence of a signed APK file. How to sign an apk file, you will learn from this article.

small digression

When my pet project got close to release, I started looking for information on how to quickly and painlessly publish an application. Many of the instructions found looked simple. I chose the instructions of the authors of the Ionic framework, on which the application was developed. Not everything worked out the first time, there are several features. The signing process is described in this article, important points are highlighted.

Initial data

I'm assuming you have everything you need set up to develop hybrid mobile applications using Apache Cordova. Must be installed:
  • Apache Cordova
  • Java Development Kit
  • Android SDK Tools
lcf is used as the project and application name. Replace with your project name where necessary.

Go

First you need to create a release build of your application. But before that, let's make sure that all unnecessary plugins are removed. For example, we do not need a plugin that prints debug information to the console. Let's remove it:

$ cordova plugin rm cordova-plugin-console
To generate a release build for Android, use the command build with flag --release:

$ cordova build --release android
This command will create unsigned APK file in directory:

platforms/android/build/outputs/apk
For example platforms/android/build/outputs/apk/ android-release-unsigned.apk. Then we need to sign this file and run the utility zipalign to optimize and prepare the file for Google Play.

A certificate is required to sign a file. Let's create it using the utility key tool which is included in the JDK:

$ keytool -genkey -v -keystore lcf.keystore -alias lcf -keyalg RSA -keysize 2048 -validity 10000
Important

The value of the -alias parameter must be remembered, but it is better to write it down. In the example above, it is equal to lcf (by the first letters of the name of the Loyal Client Free application). I will not give details here, if you are interested, write in the comments, I will tell you more.

Alias ​​is used every time when signing * applications. To make it easier to remember, use the name of the keystore file as an alias, for example:


-keystore hello-world.keystore -alias hello-world -keystore weather-app.keystore -alias weather-app -keystore todo.keystore -alias todo
* You need to sign the application with each release of updates

Utility key tool asks a series of questions. There will be 8 of them in total. To have an idea of ​​the questions and approximate answers in advance, all of them are given below, under the spoiler.

keytool questions and sample answers

1.Enter keystore password:
Here you need to enter a password for the file (at least 6 characters). The entered password must be written down in a safe place, it is needed every time when signing the application.

2. Re-enter new password:
Re-entry password.

3. What is your first and last name?
: Ivan Petrov
Your first and last name. The value in square brackets is the default value.

4. What is the name of your organizational unit?
: IT
The name of your company division. You can leave it blank, I specify IT.

5. What is the name of your organization?
: 2developers
The name of your organization. Specify if any.

6. What is the name of your City or Locality?
: Moscow
City name

7. What is the name of your State or Province?
: MO
Region name

8. What is the two-letter country code for this unit?
: EN
Code of the country. I indicate RU.

: y

Confirm if everything is correct or press Enter to enter again.


At the end, a message about the successful generation of the key will appear. You will be prompted to set a password for the private key (if you want to leave the same as for the certificate, press Enter):

Generating 2 048 bit RSA key pair and self-signed certificate (SHA256withRSA) with a validity of 10 000 days for: CN=Ivan Petrov, OU=IT, O=2developers, L=Moscow, ST=MO, C=RU Enter key password for (RETURN if same as keystore password):
The file will be created in the current directory lcf.keystore.

Important

The created file must be saved in a safe place. If you are using a private repository, then the file can be committed along with the application source codes. In general, certificates are best stored separately. If you lose your certificate, you won't be able to release app updates.

There are two steps left, and you will have an APK file ready for distribution. We proceed directly to signing.

To sign your apk file, use the utility jarsigner, which is also included in the JDK.

$ jarsigner -verbose -sigalg SHA1withRSA -digestalg SHA1 -keystore lcf.keystore android-release-unsigned.apk lcf
The name of the certificate is specified after the parameter -keystore, alias - after the file name.

Finally, to optimize the apk file, we will use the utility zipalign:

$ zipalign -v 4 android-release-unsigned.apk LoyalClientFree.apk
The last parameter is the name of the file that you will upload to Google Play.

Important.

Utility zipalign it's part of the Android SDK Tools and can be found here:

/path/to/Android/sdk/build-tools/VERSION/zipalign

Conclusion

You now have an apk file ready for distribution that can be uploaded to Google Play. Fill in the description, determine the rating of your application and feel free to click "Publish".
 
Articles on topic:
How to make notes and footnotes in Word
When formatting a document, sometimes it becomes necessary to explain the text and, accordingly, the question of how to make a footnote in Word. As a rule, it is a note to indicate the source of information or explain the main idea directly in the text
The best desktop reminder program
A site that gives +5 luck for an investor The best way to avoid repeating the mistake is to develop a rule that will allow you to remember the very rake that you stepped on. How I went into a plus, but went into a minus Without any explanation, the paragraph heading is an example
Picmonkey Photoshop is a handy online photo editor with many filters and effects.
Image editing in the cloud is gaining popularity. If earlier, in order to make a simple photo processing - remove the red-eye effect, make some kind of arrow, etc. we installed such professional
How to remove hyphens in a document
The installation of hyphenation in the Word text editor occurs automatically or manually. But sometimes it is not always necessary for the user. Therefore, in our article, we will look at several ways how to remove word wrap in Word. As practice shows,