Computers Windows Internet

How to sign an APK game or application on Android correctly. how to sign apk with gradle how to sign apk file for google play

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 apps with 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
Country code. 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".

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 you know now, without a digital signature, your creation cannot be placed on the Market, and this is already serious. A lot of young Android developers have noticed, so to speak, beginners completely forget to sign their application and try to do something with it later and that's it wondering why they are unable to perform certain actions 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.

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 backward 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 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.

There are screenshots in the article when the app store was called "Android Market". A generation of cats has already grown up who have never heard of this name. But the general principle has not changed. Left for history. I can't re-register to take new screenshots.

Since we are worried, we will practice on cats. Let's take, for example, an example from the article and try to put it on Google Play. If everything works out, then it will be easier.

Before proceeding further, make sure you have your own application icons and program name ready. It will be very strange to see a program with a standard icon and the name "HelloWorld" in the app store. And also check all the entries in the manifest file.

Step one. He is the hardest

Any application posted to the store must have a signed certificate. The certificate allows you to identify yourself as the author of the program. And if someone tries to post a program with the same name as yours, he will be denied due to a name conflict. The name of the application is the full name of the package.

When you run your applications on an emulator or your phone, the development environment automatically signs the program with a debug certificate. A debug certificate is not suitable for distribution through the store, and you need to sign the application with your own unique certificate. It's free, without registration and SMS.

Let's create a signed APK file, which is something like an executable file like notepad.exe on Windows. If you have the Android Studio development environment open, then select from the menu build | Generate Signed APK....

A wizard dialog box will appear, which you need to fill in with the data.

In the first field, specify the path to the keystore. If you have had to create programs before, including in Eclipse, you can specify an existing repository using the button Choose existing.... If you are creating a repository for the first time, then select the button Create new.... A new dialog box will appear.

In the first field, you need to select a folder using the button ... and enter a name for the storage file, which will be given the extension jks.

Now you create a key for the application. In field Alias(Nickname) enter the name of the key that you and the cats can understand. It is not necessary to create an alias for each application, you can use one alias for your applications and separate aliases for custom applications.

You also need to create a password for the key and confirm it.

The key is designed for 25 years. Field Validity (years) leave it unchanged (unless you have good reasons to the contrary).

Lastly, fill in information about yourself.

After filling in the fields, you will return to the very first window of the wizard.

Click on the button Next and in the next window enter another password to access the password database.

You may not have this step. It may appear if you have checked the "Remember password" option. I don't remember the details, you'll figure it out yourself.

The last step is to press the button Finish.

This used to be the last step. Now there are new checkboxes V1 (Jar Signature) and V2 (Full APK Signature). Check at least the first option V1- this corresponds to the old way. The second method is considered more secure in terms of hacking and can be used for later APIs, at your discretion (see below).

As a result of complex manipulations with dialog boxes, you will have the long-awaited APK - your charm, which will open the door to the world of wealth and happiness.

Pushing a button Show in Explorer, you will launch File Explorer on your computer with the folder containing the signed file.

Be careful with the generated key. It is he who guarantees that the new version of the program is written by you. Therefore, if you lose the created key, you will have to upload the program under a different name with a new key.

The studio provides a mode for automatically creating a signed application. Right click on the folder app and in the context menu select Open Module Settings. Choose a section app in section Modules. Select tab Signing. Click on the plus button and fill in the fields.

Go to tab Build Types and choose assembly release. In drop down list Signing Config select the newly created configuration. By default it has the name config.

Click OK to save the results.

You can also sign applications through the command line without the participation of the studio, if you are a pervert. You can read the documentation on this topic.

v2 Full APK

In 2017, Google changed the signing process a bit. There are now two schemes for obtaining an APK signature: v1 JAR and v2 Full APK.

The v1 signature (which has existed since the beginning) does not protect some parts of the APK, such as the ZIP metadata. The APK verifier has to handle a lot of untrusted data structures and then discard data that is not signed, which leaves 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 solve the problems, a new v2 Full APK has been developed, which you will encounter when signing your application.

Scheme v2 works in Android 7.0 Nougat (API 25). The scheme provides faster application installation and good protection against unauthorized changes to the APK. The content of the APK is hashed and signed, then the resulting APK signing block is inserted into the APK.

The new format is backward 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.

In older applications, I leave the checkbox next to the first version. Perhaps later they will force you to switch to the second version forcibly. It is 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.

Strictly speaking, you can post an apk file on your site, and all your visitors can download and install it on their phones. But this is somehow undignified in our age of nanotechnology. So let's move on to the next step.

Step two. You must Fedya, you must

The next step is very unpleasant. You need to give 25 evergreens to a stranger. So that you would not be so offended, this operation was called the registration fee. You will need a credit card with the specified amount. Please note that Visa Electron, and even more so the discount card of the Perekrestok chain of stores, will not suit you. If you already have the required card, then skip this paragraph. I can advise the rest to get a QIWI wallet and get a virtual card there. That is exactly what I did, since it was reluctant to go to the bank and write all sorts of statements.

Automatic update

If you created a new version of the program by fixing various bugs and adding new photos of a cat, then you need to increase the version number in the manifest by one (attribute versionCode) and replace versionName for yourself (will be shown on the Google Play page). In the latest versions of the studio, these properties are now not in the manifest, but in the file build.gradle module of your application. Upload the new version on Google Play and users will receive the update automatically.

Follow the reviews

Install the Google Play Developer Console app on your device so you don't miss a new review of your app. You can also view statistics.

Changing vault and key alias passwords

Haven't had to use it in a few years, so I don't know if this information is up to date.

Let's say you sold your program with source codes to another company. In order for it to post program updates, the company must sign the application with the same key that you signed. Otherwise, the program will be considered different and the package name will have to be changed. But then old users won't be able to get updates.

But if you sign all your programs with the same key and password, for example cat cat, then the company can sign your other applications with the same key by placing their programs with the same package name, and you will not prove anything to anyone.

Therefore, you need to take care of changing the key for transfer to the new owner.

Suppose our repository has the structure:

Keystore name: old.keystore Keystore password: cat1 Alias: my_alias Alias ​​password: cat2

Make a copy of your vault and save it elsewhere. This should have been done during the first creation, because if you lose storage, you will not be able to restore access to your programs during the update.

Make a copy of your repository again and rename it, for example, new.keystore. We will work with him.

Run the utility key tool with command:

Keytool -storepasswd -keystore new.keystore

You will be prompted to enter your current password and then enter a new password and repeat it. Approximately like this:

Enter keystore password: New keystore password: Re-enter new keystore password:

The first part of the task has been completed, the vault password has been changed.

If you also want to change the password for the alias, then run the utility again with the command:

Keytool -keypasswd -keystore new.keystore -alias my_name

You will be asked to enter your current vault password (your new password), then the alias password. You can enter a new password and it will replace the old password.

Enter keystore password: Enter key password for

Alias ​​password changed.

If changing the password is not enough for you and you want to change the name of the alias (maybe you used the name of your favorite cat, why should others know about it), then we continue to work.

We run the command:

Keytool -changealias -keystore new.keystore -alias my_alias -destalias my_new_alias

You will be asked to enter the vault password, then the password for the new alias (the current password), then the new password and repeat it. The alias name will be changed.

So, it took us three steps to create a new repository and an alias to transfer to a stranger. The new owner should do the same to make sure you don't take advantage of the changed files. However, this is his problem.

We sign the finished application

Such a case can turn up when you have lost the source code and have only APK. This is most likely true for pirates who re-sign other applications (do not do this with other people's programs).

First, change the extension from apk to zip. Delete the folder in the archive META-INF. Restore the extension. You have deleted the old signature.

Now you need to sign the application with a new key. Enter a command.

jarsigner -keystore keystore-file.jks -storepass keystore_password -keypass alias_password --signedjar signed-apk-file.apk apk-file.apk alias_name

If successful, you will receive a message that the application is signed. Next, we execute another command.

ANDROID_SDK_PATH/build-tools/LAST_BUILD_TOOLS_VERSION/zipalign -v 4 signed-apk-file.apk aligned-apk-file.apk

The result should be an APK file signed with the new key. Never used it myself.

Google key storage

In 2017, Google added a new option to store keys in the cloud. The main difference is that you sign the app with a special upload key, which Google verifies and removes, replacing it with the original app signing key you provided.

It allows you to manage app signing keys for both new and published apps, which will be stored by Google in their own key store. To join this program, you must subscribe to it in your Google Play Console. It is worth noting that it will no longer be possible to unsubscribe from it.

This method is very useful - if the key store is lost, Google Play App Signing will allow you to reset the key to install a new one. You don't have to republish the app with a new package name and key.

Additional reading

Android-keystore-password-recover by MaxCamillo - If you have lost your password, then try using this tool. I haven't used it myself, so I won't tell.

Last update: 10/30/2015

After creating the application, testing and debugging it, we can start publishing it. The essence of the publication is to create a file with the extension .apk, which will represent the application, and its subsequent placement in the Google Play Market or other external sites. By default, during the process of debugging and creating an application, the apk file is already created, and we can find it in the project folder along the path Project_name\app\build\outputs\apk. By default, the file is named app-debug.apk and represents the debug version.

But for a full publication of this file may not be enough. And we still need to do some preparation of the project for release. To do this, specify in the manifest file for the element android:versionCode and android:versionName attributes are set. Also in the manifest file the element must not contain the android:debuggable attribute

In addition, at this stage, you can set an icon for the application that will be displayed on the gadget's home screen, the name of the application (the android:label attribute on the element), and you can also set the license agreement.

The manifest file must also define the name of the package (the package attribute of the element ), which will be used for the application later. By default, when developing in Android Studio, app packages start with com.example. You should not leave this name, as the name of the package will serve as a unique identifier for your application. For example, below in my case the package name is "com.maverics.eugene.telephonelist":

Moreover, if in the java code files, the package name at the beginning of the file must also correspond to the application package.

Setting Requirements

You can also set API requirements during the pre-release phase. For example, our application has a certain minimum version of the Android OS, so we can set the corresponding attributes on the element in the manifest file

    android:minSdkVersion - minimum Android version

    android:targetSdkVersion - the optimal API version

    android:maxSdkVersion - maximum system version

For example, let's say the minimum version of Jelly Beans is 4.1.2, and the optimal version is KitKat 4.4.4:

//.............................

Application signature

When everything is ready, the Android application must be signed with a certificate, thanks to which the author of the application can be identified. When we test an application by installing it through Android Studio on a device, it is signed automatically. But to create a release version, we need to perform an additional series of actions.

When creating a certificate, keep in mind that when you update the application, the system will compare the certificates of the old and new versions. And the update will occur if the certificates of both versions match. But if the new version is signed with a new certificate, then the application will be treated as completely new, unrelated to the old version and representing a completely different application. In this case, in order to install it, the new version will have to have a different package name than the old one.

First, in Android Studio, select Build -> Generate Signed APK from the menu. This will open the wizard window:

Click on the Create new... button. After that, a window for creating a key will open:

Enter the path to the network certificate file to be created in the Key store path field. If the specified folder does not exist, create it or define an existing folder.

Specify the password in the Password/Confirm field.

Specify an alias in the Alias ​​field. You can put an arbitrary name.

In the First and Last Name field, enter the first and last name. And then we write the unit, organization, city, country and country code.

At the end, click OK.

After that, the first window will be automatically updated:

The final window will show us the path to the directory where the signed apk application will be located in the release version. Click on Finish.

Now, in the specified path, you can find a signed apk, which will have the name app-release.apk:

We can rename the file, keeping its extension and upload it to the Play Market or any site, or download it directly to your mobile device. After downloading to your phone / tablet, just click on it, and using the standard package installer, the application will be installed. True, here we also need to take into account that if we install the application not from the Play Market, then in the settings we need to allow installation from other sources - Security-> Unknown sources (Allow installation of applications from other sources)