Android signature mechanism

Source: Internet
Author: User
Tags pkcs7 sha1

1.android Why to sign all Android applications require a developer to digitally sign a certificate, and the anroid system does not install a program that is not signed. Usually our program can be installed and run on the emulator, because during application development, because the debug interview is compiled, so ADT will automatically use the default key and certificate to sign, and in the release mode, the APK file will not be automatically signed. This requires a manual signature.
Signing the APK can provide the following benefits:
1. Application Upgrade: If you want users to seamlessly upgrade to a new version, you must sign with the same certificate. This is because only the same certificate is signed and the system is allowed to install the upgraded application. If you have a different certificate, your application will be asked to take a different package name, in which case it is equivalent to installing a completely new application. If you want to upgrade the application, the signing certificate must be the same, the package name is the same!
2. Application modularity: The Android system can allow multiple applications signed by the same certificate to run in one process, and the system actually takes them as a single application, at which point we can deploy our application as a module, and the user can upgrade one of the modules independently.
3. Code or data sharing: Android provides a signature-based permission mechanism, so one application can expose its functionality to another application that is signed with the same certificate. By signing multiple applications with the same certificate and leveraging signature-based permission checks, you can share code and data in a secure way between applications.
between different applications, want to share data, or share code, then let them run in the same process, and let them sign with the same certificate.

2. Signature method Reference: Method of Signature,There's no way of detailing signatures here.
3. Principle of signature mechanism
3.1 Basic knowledge
Message digest-message Digest
Short summary, please see English translation, is a summary, not a signature, almost all of the online APK signature analysis of the article has confused the two concepts. Simply said message digest is on the message data, execute a one-way hash function, generate a fixed-length hash value, this hash value is a message digest is also called Digital fingerprint, Message digest has the following characteristics:
1. The message itself cannot be inferred from the digest
2. If the message is modified, then the digest must change (in fact, because the long plaintext generates a short digest of the hash will inevitably have a collision), so this sentence is not accurate, we can instead: it is difficult to find a pattern, modify the message, and its digest does not change (conflict-resistant).
This feature of the message digest is good for verifying the integrity of the data, such as downloading a large file bigfile during network transmission, We will download Bigfile and BIGFILE.MD5,BIGFILE.MD5 from the network at the same time to save the Bigfile summary, we generate the Bigfile message digest locally, and BIGFILE.MD5 compare, if the content is the same, the download process is correct.
Note that the message digest only guarantees the integrity of the message and does not guarantee the non-tampering of the message.

md5/sha-0 SHA-1
These are summary generation algorithms, which are not related to signatures. If you have to say that they are related to the signature, it is to use the abstract technology.

Digital Signature-Signature
Digital signature, Baidu Encyclopedia on the digital signature has a very clear introduction. Digital signature is the sender of information with their own private key to the message digest encryption to produce a string, encryption algorithm to ensure that others can not forge the generation of this string, which is also the sender of information to send information authenticity of a valid proof. Digital signature is a combination of asymmetric key encryption technology + Digital Digest technology.

The technology of digital signature is to encrypt the information digest with the sender's private key and send it to the receiver with the original text. The recipient only uses the sender's public key to decrypt the encrypted message digest, and then the recipient uses the same hash function to generate a message digest of the received text, which is compared to the decrypted message digest. If the same, the information received is complete, not modified during transmission, the difference is that the information has been modified, so the digital signature can guarantee the integrity of the information. And since only the sender has the private key of the cryptographic digest, we can be sure that the information must be sent by the sender.

Digital Certificates-Certificate
A digital certificate is a file that is digitally signed by the Certificate Authority center that contains public key owner information and a public key. CERT. RSA contains a digital signature and a digital certificate.
Note that the CERT.RSA certificate in the Android APK is self-signed and does not require that the certificate be issued or certified by a third-party authority, and the user can generate the self-signed certificate on the local machine itself.
3.2 Android Signature Analysis We will change the df_sdm_1008.apk (optional) file to Df_sdm_1008.zip file, open the Df_sdm_1008.zip file, 1.

Figure 1 Df_sdm_1008.zip File
1. meta-inf\ (Note: Post-signature information);
2. Res\ (Note: The directory where the resource files are stored);
3. Androidmanifest.xml (Note: Program global configuration file);
4. Classes.dex (Note: Dalvik byte code);
5. RESOURCES.ARSC (Note: Compiled binary resource file).
Next, analyze for the meta-inf\ file.
3.3meta-inf\ file meta-inf\ file has three files, respectively MANIFEST.MF, CERT. SF, CERT. As shown in rsa,2. Now there is a question of how the three files produced--the signature produced, the second question of how the signature is done? Here Android provides the APK signature tool signapk, via Xxx.keystore (Java KeyStore, used for communication encryption, such as digital signatures. KeyStore is the information that is used to hold the key pair, such as the public key and the private key, to sign the APK, generate the meta-inf\ file, and refer to article 4.
1.MANIFEST. MF File First look at the source code
MANIFEST. MF            Manifest Manifest = adddigeststomanifest (Inputjar);            Je = new Jarentry (jarfile.manifest_name);            Je.settime (timestamp);            Outputjar.putnextentry (JE);            Manifest.write (Outputjar);

/** ADD The SHA1 of every file to the manifest, creating it if necessary.        */private static Manifest Adddigeststomanifest (Jarfile jar) throws IOException, Generalsecurityexception {        Manifest input = Jar.getmanifest ();        Manifest output = new Manifest ();        Attributes main = Output.getmainattributes ();        if (input! = null) {Main.putall (Input.getmainattributes ());            } else {main.putvalue ("manifest-version", "1.0");        Main.putvalue ("created-by", "1.0 (Android signapk)"); }<span style= "White-space:pre" &GT;&LT;/SPAN&GT; for (Jarentry entry:byName.values ()) {String            Name = Entry.getname (); if (!entry.isdirectory () &&!name.equals (jarfile.manifest_name) &&!name.equals (Cert_sf_nam                 E) &&!name.equals (cert_rsa_name) && (Strippattern = = NULL | | !strippattern.matcher (name). Matches ())) {inPutstream data = Jar.getinputstream (entry);                while (num = data.read (buffer)) > 0) {md.update (buffer, 0, num);                } Attributes attr = null;                if (input = null) attr = input.getattributes (name); attr = attr! = null?                New Attributes (attr): New Attributes ();                Attr.putvalue ("Sha1-digest", Base64.encode (Md.digest ()));            Output.getentries (). Put (name, attr);    }} return output; }
Iterate through each of the files in the APK package and generate summary information for these files using the SHA1 algorithm. validation is the SHA1 algorithm used by all files: 1. Installing the Hashtab tool
2. Open the MANIFEST.MF file for an example:
name:androidmanifest.xmlsha1-digest:zovq4avmccjfkilzllhgmeolvnu=
It finds the Androidmanifest.xml file in the file and looks at its corresponding hash value, as shown in 3. Here the 16 binary 668beae0054c7028c59082d92e51e099e38bbe75 is removed and the 16 binary is converted to the corresponding Base64 code via the online transcoding website: hex to base64, see " Zovq4avmccjfkilzllhgmeolvnu= "is relative to the record information.

2.CERT. SF file First look at the source code
CERT. SF            Signature Signature = signature.getinstance ("Sha1withrsa");            Signature.initsign (Privatekey);            Je = new Jarentry (cert_sf_name);            Je.settime (timestamp);            Outputjar.putnextentry (JE);            Writesignaturefile (Manifest,                    new Signatureoutputstream (Outputjar, signature));

/** Write A. SF file with a digest of the specified manifest. */private static void Writesignaturefile (Manifest Manifest, signatureoutputstream out) throws IOException,        generalsecurityexception {Manifest SF = new Manifest ();        Attributes main = Sf.getmainattributes ();        Main.putvalue ("Signature-version", "1.0");        Main.putvalue ("created-by", "1.0 (Android signapk)");        Base64encoder base64 = new Base64encoder ();        MessageDigest MD = messagedigest.getinstance ("SHA1");                PrintStream print = new PrintStream (new Digestoutputstream (New Bytearrayoutputstream (), MD),        True, "UTF-8");        Digest of the entire manifest manifest.write (print);        Print.flush ();        Main.putvalue ("Sha1-digest-manifest", Base64.encode (Md.digest ()));        map<string, attributes> entries = Manifest.getentries (); For (map.entry<string, attributes> entry:entries.entrySet ()) {//DigesT of the manifest stanza for this entry.            Print.print ("Name:" + entry.getkey () + "\ r \ n");  For (Map.entry<object, object> att:entry.getValue (). EntrySet ()) {Print.print (Att.getkey () + ":" +            Att.getvalue () + "\ r \ n");            } print.print ("\ r \ n");            Print.flush ();            Attributes sfattr = new Attributes ();            Sfattr.putvalue ("Sha1-digest", Base64.encode (Md.digest ()));        Sf.getentries (). Put (Entry.getkey (), sfattr);        }<span style= "White-space:pre" ></span>//signature information is not used on the above to Sf.write (out); A bug in the Java.util.jar implementation of Android platforms//up to version 1.6 would cause a spurious ioexce        Ption to being thrown//if the length of the signature file is a multiple of 1024x768 bytes.        As a workaround, add an extra CRLF in the case.            if ((out.size ()%) = = 0) {out.write (' \ R ');        Out.write (' \ n '); }    }
Although Writesignaturefile literally appears to be a signature file, the CERT.SF generation and the private key do not have a penny relationship, and in fact should not have a penny relationship, this file naturally does not save any signature content. CERT. SF holds the digest value of MANIFEST.MF (the first item),
signature-version:1.0created-by:1.0 (Android) sha1-digest-manifest:ngpbbfoira4fsy0pn0dbonop5bq=
and a summary value for each summary item in the MANIFEST.MF. I don't know why I'm introducing cert.sf, and I actually think the signature can be generated with MANIFEST.MF.
Verify that all the summaries are MANIFEST.MF entries
First of all: corresponding MANIFEST.MF file, the corresponding message digest is sha1-digest-manifest:ngpbbfoira4fsy0pn0dbonop5bq=, as shown in the actual message digest 4.
Figure 4 MANIFEST. MF Message digest and corresponding Base64 encoding
Secondly: message digest for validation entry, according to the algorithm of the entry message digest, knows the content format is SHA1 ("Name:filename" +cr+lf+ "Sha1-digest:" +sha1 (file_content) +CR+LF+CR+LF) I'm going to take one of the cert.sf out and then verify that it's taken out
name:androidmanifest.xmlsha1-digest:pjblxoolyykhhlr/0lkzkk2dkm0=
In the MANIFEST.MF entry, save as "new text document. txt" to view the corresponding message digest and convert it to Base64 encoding, as shown in 5. Figure 5 Creating a new text document the message digest and corresponding base64 code for the. txt are validated for CERT.SF.
3.CERT. RSA file Code for
            CERT. RSA            JE = new Jarentry (cert_rsa_name);            Je.settime (timestamp);            Outputjar.putnextentry (JE);            Writesignatureblock (signature, PublicKey, Outputjar);

    /** Write A. RSA file with a digital signature. *    /private static void Writesignatureblock (            Signature Signature, X509Certificate publickey, outputstream out) C3/>throws IOException, generalsecurityexception {        signerinfo signerinfo = new SignerInfo (                new X500Name ( Publickey.getissuerx500principal (). GetName ()),                Publickey.getserialnumber (),                algorithmid.get ("SHA1"),                algorithmid.get ("RSA"),                signature.sign ());        PKCS7 PKCS7 = new PKCS7 (                new algorithmid[] {algorithmid.get ("SHA1")},                new ContentInfo (Contentinfo.data_oid, NULL),                new x509certificate[] {PublicKey},                new signerinfo[] {signerinfo});        Pkcs7.encodesigneddata (out);    }
This file holds the signature and the public key certificate. Signature generation must have a private key to participate in, the signature information digest is CERT.SF content.
Signature this data is used as a digest of the signature, the Writesignatureblock function uses Privatekey to generate a signature for signature encryption, and then saves the signature and the public key certificate in Cert.rsa.
Finally saved in Cert.rsa is the CERT.SF digital signature, signed using Privatekey generated, the signature algorithm is defined in PublicKey. It also stores publickey in Cert.rsa, which means that Cert.rsa contains the certificate used for signing and signing. and requires that the certificate be self-signed.
Extracting Cert.rsa Information: Refer to RSA public key information, subject information, corresponding signature information.
Certificate:data:version:3 (0x2) Serial number:1281971851 (0x4c69568b) Signature Algorithm:sh            A1withrsaencryption Issuer:cn=michael Liu validity not Before:aug 15:17:31 GMT Not After:aug ten 15:17:31 2035 GMT subject:cn=michael Liu Subject public Key info:public K EY algorithm:rsaencryption RSA Public Key: (1024x768 bit) modulus (1024x768 bit): 00                    : 8d:04:84:a2:1e:c6:56:39:f2:cd:a6:f0:48:a5:f7:5e:71:8f:e1:a8:af:a7:dc:66:92:a2:b9:cf:da:                    0F:32:42:CE:83:FE:BC:E1:4F:0A:FD:D9:A8:B3:73:F4:FF:97:15:17:87:D6:D0:3C:DA:01:FC:11:40:7D: 04:da:31:cc:cd:da:d0:e7:7b:e3:c1:84:30:9f:21:93:95:20:48:b1:2d:24:02:d2:b9:3c:87:0d:fa:b 8:e1:b1:45:f4:8d:90:0a:3b:9d:d8:8a:9a:96:d1:51:23:0e:8e:c4:09:68:7d:95:be:c6:42:e9              : 54:a1:5c:      5d:3f:25:d8:5c:c3:42:73:21 exponent:65537 (0x10001) Signature algorithm:sha1withrsaencryption        78:3C:6B:EF:71:70:55:68:28:80:4D:F8:B5:CD:83:A9:01:21:2A:C1:E4:96:AD:BC:5F:67:0C:CD:C3:34:51:6D:63:90:A9:F9: D5:5e:c7:ef:34:43:86:7d:68:e1:99:87:92:86:34:91:6d:67:6d:b2:22:e9:5e:28:aa:e8:05:52:04:6e:4e:d4:7f:0f:b0:d6 : 28:f5:2b:11:38:d5:15:cb:e3:e4:c9:99:23:c1:84:4f:ce:69:e9:b1:59:7b:8e:30:01:1c:e1:92:ee:0d:54:61:29:f5:8e: 9e:42:72:26:2b:aa:c7:af:d9:c9:d1:85:95:8e:4c:8d:5c:77:c5:ce:4e

Reference article:

1.Android Why to sign the app

2. How to sign

3. Message digest, digital signature, digital certificate

4.SIGNAPK Project

5. Extracting public key and signature information from the Cert.rsa




Android signature mechanism

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.