O'Reilly logo

Programming Android by Zigurd Mednieks, G. Blake Meike, Masumi Nakamura, Laird Dornin

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

Chapter 4. Getting Your Application into Users’ Hands

This chapter covers everything it takes to get your application into users’ hands. Earlier in this book, we told you everything you needed to get started reading example code and creating simple programs. Here, we complete the picture, with all the other operations you need to perform to widely distribute your applications, sell them (if that is your aim), and subsequently get paid by Google, which operates the Android Market.

You may not be ready to put your application into the Android Market, but keeping this process in mind will shape the way you design and implement your application. Commerce has considerations that are distinct from most other aspects of software development, including identifying yourself to the Android Market and to your customers, obtaining permission to use certain APIs, protecting your identity, and preparing your app to be run on a variety of hardware as well as being updated over time.

Application Signing

Application signing, or code signing, enables Android devices, the Android Market, and alternative means of distribution to know which applications originate with the owner of a signing certificate, and to be certain the code has not been modified since it was signed.

Public Key Encryption and Cryptographic Signing

Public key cryptography depends on this mathematical principle: it is easy to multiply large prime numbers together, but it is extremely difficult to factor the product of large primes. The multiplication might take milliseconds, while factoring would take hundreds to millions of years and would require an astronomically large computer.

This asymmetry between multiplication and factoring means that a key made with the product of two large prime numbers can be made public. The knowledge that enables encrypted messages to be decrypted is the pair of large primes that are part of the private key. That means that documents encrypted with the public key are secure, and only the possessor of the private key can decrypt them.

Signing, which is what we will do to Android applications, depends on related properties of public key encryption.

The steps to sign a document are:

  1. Compute a unique number—a hash—from the document. This is also known as a message digest.

  2. “Encrypt” the message digest with the signer’s private key. This is the signature.

Voilà! You now have a number—a signature—that is tied to the document by the hashing algorithm, and tied to the signer’s private key.

The steps to verify a signed document are:

  1. Compute a unique number—a hash—from the document.

  2. “Decrypt” the signature using the public key, which should also result in the same number as the hash.

Now you know some interesting facts: the document—in our case, an application—came from the person with the private key corresponding to the public key you used in the verification. And you know that the document was not altered; otherwise, the hash decrypted from the signature would not be the same as the one computed from the document.

Verifying a signature also verifies that the signature was not copied to a different document. Signatures are unalterably tied to the document from which they were created.

Tip

You may have noticed we put the words encrypt and decrypt in quotes when we said the message digest, or hash, is encrypted. This is because it’s not encryption in the way you normally use a public-private key system—to keep prying eyes away from a message by encrypting it with the public key so that only the person with the private key can read the message.

Here, “encrypt” just means “compute a number.” You are not hiding information when you “encrypt” a hash or message digest with a signer’s private key. The reason you use the words encrypt and decrypt is that you get the same hash or message digest when you decrypt with the public key.

Anyone with the public key and a published algorithm can “decrypt”—which is the point in verification: to see that you got the same hash the sender signed, which also proves that the sender is in possession of a private key corresponding to the public key, and proves that the document is what the sender signed.

Because verification can be computed using a public key, your Android system—and any other interested party—can verify that an application was signed with a particular key and that it was not modified since it was signed.

More generally, any electronic document—any set of bits—can be cryptographically signed, and cryptographic signatures, or “digital signatures,” can be used to sign documents in a way that can legally substitute for a person’s handwritten signature.

How Signatures Protect Software Users, Publishers, and Secure Communications

As a user of computer software, you may already have been thinking, “It would be nice to know where my software comes from and that it has not been modified en route to my device.” Signed applications enable you to have this confidence. This is a form of confidence based on cryptographic signatures similar to one you already use. When you browse the Web you already rely on cryptographic signatures to trust that the ecommerce site you are communicating with is authentic, and not a rogue impostor set up to take your money and run. In the case of ecommerce, the client verifies a signature of the server’s certificate using a public key from a certificate authority. Your browser comes with keys from several certificate authorities used for this purpose.

The role of the certificate authority is to consolidate the number of parties you need to trust: you trust your browser vendor to use only keys from reputable certificate authorities, and ecommerce vendors obtain certificates from authorities browser vendors trust. The certificate authorities have a responsibility to verify that the people claiming to be, for example, Amazon.com are, in fact, Amazon.com. Now, when your browser initiates a secure session with Amazon.com, you know two things: your data is secured from eavesdropping by encryption that only the ecommerce vendor’s server can decrypt, and you are reasonably sure that the server you are connecting to is using a certificate issued by a certificate authority to the company you want to communicate with, because the certificate authority has taken steps to assure itself that it issues certificates to known parties.

Self-signed certificates for Android software

In signing Android software, the signing certificate does not have to come from a certificate authority. It can be created by the software publisher—in this case, you. Unlike ecommerce transactions, where you have the additional requirement that you want to ensure that each and every connection your browser makes is to the authentic Amazon.com, perhaps through a link of unknown provenance, the act of using software does not depend as critically on knowing the identity of the signing party.

For organizations considering using a signature issued by a certificate authority, the Google documentation explicitly mentions that there is no need to have your application signed using a certificate authority, and that self-certification is the informal standard for Android applications.

In addition to initially verifying application developer identity, digital signatures on Android are also used during application upgrades to ensure that an application upgrade should be permitted to access files created by an earlier version of the application, and that the upgrading application is not actually a malicious application trying to steal user data.

As long as you are confident that updates to the software come from the same party you obtained the software from in the first place, you can be reasonably sure the programs you are using are safe, and that the publisher of that software is known to the distributor of the software, which is the Android Market.

In addition to the assurance of updates from the original publisher, Android applications are sandboxed and require permissions, as described at http://developer.android.com/guide/topics/security/security.html, to access functionality that could compromise your data or cause chargeable events on your mobile service.

Signing an Application

The concepts behind cryptographic signing are subtle and complex. But the complexity is managed by the SDK tools. When you compile and run Android code on a device or on an emulator, you are running signed code.

Debug certificates

If you have been following the examples in this book and have created an Android project and run it in an emulator or device, you may have noticed you didn’t need to create a certificate and that your application is installable on an Android handset, despite the fact that all Android code must be signed. This convenience is achieved through the use of an automatically created debug certificate. Let’s take a look at the debug certificate.

Look in the android folder in your home folder. There you will find a file named debug.keystore. Using the keytool command, you can find out what is inside this file:

keytool -list -keystore debug.keystore                

When you are prompted for a password, enter android. You will see output that looks like this:

Keystore type: JKS
Keystore provider: SUN

Your keystore contains 1 entry

androiddebugkey, May 13, 2010, PrivateKeyEntry, 
Certificate fingerprint (MD5): 95:04:04:F4:51:0B:98:46:14:74:58:15:D3:CA:73:CE                

The keystore type and provider indicate the keystore is a Java keystore, compatible with the Java Cryptography Architecture and Java classes that enable Android to use code signing and other cryptography tools. More information on the Java Cryptography Architecture is available at http://download.oracle.com/javase/6/docs/technotes/tools/solaris/keytool.html.

The keytool command is part of the JDK, and is described briefly in keytool and in greater detail at http://developer.android.com/guide/publishing/app-signing.html#cert. Detailed documentation on keytool can also be found at http://download.oracle.com/javase/6/docs/technotes/tools/solaris/keytool.html.

The last line produced by the list option in keytool is a certificate fingerprint. This is a unique number generated from a key. You will see one way in which this number is used in Google Maps API Keys, where you will use it to get an API key.

This certificate expires in a short enough interval that it cannot be used to distribute Android software other than for testing. Do not mistake the convenience of using a debug certificate for signing software as an indication that you can do without a signing certificate for distributing your applications!

Creating a self-signed certificate

Ready to sign some code for release? First, create a private key using the keytool command thusly:

keytool -genkey -v -keystore my-release-key.keystore -alias alias_name \
  -keyalg RSA -keysize 2048 -validity 50000

Note

The \ character indicates a line break, and is valid for multiline commands on Unix and Mac OS X. However, you will need to type this all on one line without the \ on Windows.

You can substitute a name of your choice for my-release-key and an alias of your choice for alias_name. The -keysize and -validity parameters should remain as shown in the preceding code.

As shown in the following code, keytool will ask you for a password for the keystore, which you will need to remember when accessing it, and a series of questions about you, your organizational structure, and your location. keytool generates a private key, usable as a signing certificate with a valid life span of about 150 years, and puts it in the file named my-release_key.keystore:

example-user@default-hostname:~$ keytool -genkey -v \
  -keystore example-release-key.keystore -alias example_alias_name \
  -keyalg RSA -keysize 2048 -validity 50000
Enter keystore password:  
Re-enter new password: 
What is your first and last name?
  [Unknown]:  Example Examplenik
What is the name of your organizational unit?
  [Unknown]:  Example
What is the name of your organization?
  [Unknown]:  Example
What is the name of your City or Locality?
  [Unknown]:  Example
What is the name of your State or Province?
  [Unknown]:  Massachusetts
What is the two-letter country code for this unit?
  [Unknown]:  US
Is CN=Example Examplenik, OU=Example, O=Example, L=Example, ST=Massachusetts, 
    C=US correct?
  [no]:  yes

Generating 2,048 bit RSA key pair and self-signed certificate (SHA1withRSA) with a 
    validity of 50,000 days for: CN=Example Examplenik, OU=Example, O=Example, 
    L=Example, ST=Massachusetts, C=US
Enter key password for <example_alias_name>
    (RETURN if same as keystore password):  
Re-enter new password: 
[Storing example-release-key.keystore]

You now have a valid key in a keystore.

Don’t lose it!

While cryptographic digital signatures are, in many ways, more reliable and secure than a handwritten signature, there is one way in which they differ: you can lose your ability to sign a document digitally.

If you lose your signing certificate, you lose your identity to Android devices and the Android Market. This means that, despite the fact that you compile and release the same code as before, you cannot use these newly compiled applications to update applications in the field, since neither Android devices nor the Android Market will recognize you as the same publisher.

Keep multiple backup copies of your signing certificate on multiple types of media, including paper, in multiple locations. And keep those backups secure. If your signing certificate is used by people other than you, they can replace your programs on your customers’ Android devices.

Detailed recommendations from the Android Developers site regarding securing your signing certificate are available at http://developer.android.com/guide/publishing/app-signing.html#secure-key.

Tip

Conversely, your cryptographic signature is your signature solely because it is in your possession. Up to the time you want to publish an Android application and continue to be identified as the publisher, you can generate, use, and discard signatures as much as you like. Don’t be afraid to experiment and learn!

Using a self-signed certificate to sign an application

Now it’s time to sign an application. In Eclipse, select the project of the application you want to sign for release, and select the FileExport command. “Why the ‘export’ command?” you may ask. After all, if you want to give someone your app to try out, you can just give her a copy of the .apk file in the bin directory of the project file hierarchy. It is as arbitrary as it seems: the “export” dialog is a grab bag of functionality, and it was a convenient place to put a procedure that isn’t quite the same as “deploying.”

In this example we use the TestActivity project, but you can use any application—your own, or any project from the examples in this book.

You will be presented with a list of options for exporting, organized into folders. Select the Android folder and select Export Android Application (as shown in Figure 4-1), and click on the Next button.

“Exporting” an Android application

Figure 4-1. “Exporting” an Android application

First, you will see if your application has any errors in configuration that might prevent it from being ready to publish, such as having the debuggable attribute set to true in the manifest. If your app is ready to go, you will see the dialog in Figure 4-2, which displays no errors.

An Android application that has no problems preventing signing and publishing

Figure 4-2. An Android application that has no problems preventing signing and publishing

Subsequent dialog boxes in this multistep sequence focus on signing. The information requested mirrors the information you entered to create your release key in Creating a self-signed certificate.

Next, you will select your keystore, as shown in Figure 4-3. The keystore is the file holding your key.

Selecting the keystore

Figure 4-3. Selecting the keystore

Once you have entered the name of the keystore and the password, click Next and proceed to the next step: selecting the alias of the key, and entering the password for the alias, as shown in Figure 4-4.

Selecting the key alias

Figure 4-4. Selecting the key alias

If you followed the steps in Creating a self-signed certificate, you have only one key, with one alias, in your keystore. Enter the password and click Next. The next step is to specify the destination .apk file and pass some checks to determine if anything else might be wrong with your app. If everything is in order, you will see a screen resembling that shown in Figure 4-5.

When you click Finish you will get a signed .apk file in the specified location.

Selecting the destination, and final checks

Figure 4-5. Selecting the destination, and final checks

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required