Android signature finishing

来源:互联网 发布:java公司笔试题 编辑:程序博客网 时间:2024/05/12 07:30


Android signature finishing

Tag: Attributes, Android, encryption, android-ViewGroupCategory: android Author: wangyz2004Date: 2013-05-20

Why to be signed

1) the sender's identity authentication
Not be replaced because the developers may use the same package name to confuse replace an installed program, in order to ensure a different signature package

2) to ensure the integrity of the information transmitted
The signature for each file in the package is processed in order to ensure that the contents of the package is not replaced

3) prevent the transaction repudiation Market software

(2) a description of signature

1) All applications must have a digital certificate, Android system does not install a digital certificate applications

2) the Android package digital certificate can be self-signed, you do not need an authoritative digital certificate authority-signed certificate

3) If you want to officially released an Android application, you must use a suitable private key to generate a digital certificate to sign to the program, and can not use the ADT plugin or ant debug tool to generate certificates to publish

4) digital certificate is valid, Android will check the certificate is valid only when the application is installed.If the program is already installed on your system, even if the certificate expires it will not affect the normal function of the program

5) after signature zipalign optimization program

6) Android digital certificates used to identify the application of and to establish a trust relationship between applications, rather than be used to determine the end-user which applications can be installed

Signature



Signed relevant documents

1)         apkpackage signature file in the META_INF directory under
CERT.SF: the key is generated for each file
TheMANIFEST.MF: digital signature information
xxx.SF: This is aJARfile signature file placeholder xxx identifies the signer
xxx.DSA: output file signatures and public key

2)         Related Items
development / tools / jarutils / src / com.anroid.jarutils / SignedJarBuilder.java
frameworks / base / services / java / com / android / server / PackageManagerService.java
frameworks / base / core / java / android / content / pm / PackageManager.java
frameworks / base / cmds / pm / src / com / android / commands / pm / Pm.java
dalvik / libcore / security / src / main / java / java / security / Sign *
build / target / product / security / platform. *
build / tools / signapk / *



5. Signature

Usually the installation prompts error:INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES

1)         Two applications with the same name and different signature

2)         Upgrade the previous version of the signature, the latter version is not signed

3)         Upgrade the previous version to DEBUG signature, after a custom signature

4)         Upgrade the previous version of theAndroidsource code signature, after a signature to DEBUG or custom signature

5)         Installing an unsigned program

6)         Install the upgrade program has passed the validity of



6.



7 Reference



1)         View a x509 certificate effective date
In SignApk.java the print outpublicKey.getNotAfter ()can be

a)          The default signature in the use of the source code
Generally in the source code compiled using the default signature, a source directory with
The $ mm showcommandsbe able to see the signature command
The Androidoffers program signapk.jar signature used as follows:
$ Signapk publickey.x509 [. Pem] privatekey.pk8 input.jar output.jar
* X509.pemto x509format public key PK8 theprivate key
build / target / product / securitydirectory, four sets of default signature:testkey, platform, shared, media(see README.txt) specific applicationAndroid.mka LOCAL_CERTIFICATEfields, which specify which key signature is not specified, the defaultTestKey.

b)         Self-signed in the source code
Androidprovides a the script mkkey.sh (build / target / product / security /mkkey.sh) used to generate keys generated by theAndroid.mk LOCAL_CERTIFICATEfield is named in the application which signature

c)          mkkey.shIntroduction

                                       i.              Generate the public
openssl genrsa -3-out testkey.pem 2048
Wherein -3 is a parameter of the algorithm, key length,2048, testkey.pemoutput file

                                      ii.              Turn into x509 format (including of validity)
openssl req-new-X509-kEY testkey.pem-out testkey.x509.pem-days 10000-subj '/ C = U.S. / ST = California / L = Mountain '

                                    iii.              Generate the private key
openssl pkcs8-in testkey.pem-topk8-outform DER-out testkey.pk8-nocrypt
The format converted toPKCS # 8is specified here the-nocryp not encrypted, so do not enter a password when signing


Read RSA key information and obtain keystore fingerprint information

    import sun.security.pkcs.<strong style="color: black; background-color: rgb(160, 255, 255);">PKCS7</strong>;      import java.io.FileInputStream;      import java.io.FileNotFoundException;      import java.io.IOException;      import java.io.InputStream;      import java.security.GeneralSecurityException;      import java.security.cert.X509Certificate;      public class SignApk {          public static X509Certificate readSignatureBlock(InputStream in) throws IOException, GeneralSecurityException {              <strong style="color: black; background-color: rgb(160, 255, 255);">PKCS7 pkcs7</strong> = new <strong style="color: black; background-color: rgb(160, 255, 255);">PKCS7</strong>(in);              return <strong style="color: black; background-color: rgb(160, 255, 255);">pkcs7</strong>.getCertificates()[0];          }          public static void main(String[] args) throws FileNotFoundException, IOException, GeneralSecurityException {              X509Certificate publicKey = readSignatureBlock(new FileInputStream("./CERT.RSA"));              System.out.println("issuer:" + publicKey.getIssuerDN());              System.out.println("subject:" + publicKey.getSubjectDN());              System.out.println(publicKey.getPublicKey());          }      }  

The output is as follows:

issuer:CN=Sodino  subject:CN=SodinoChen  Sun RSA public key, 1024 bits    modulus: 154308594144468705348294760484396264219304223307125368116140288659005422830114898674784044956357283073098453132761265419031547660249768235885852151387544779929680291539693130807734777897342583741160281523340554669518353638961667015615312475350767041053961957188628650343640790505255765999004862716823611888529    public exponent: 65537

Readable specify the the APK package of signature information, use the following command:

jarsigner-verify-verbose-certs <your_apk_path.apk>

Furthermore, access to for a keystore fingerprint information can use the following command:

  1. D :/> keytool-list-alias alias_name-keystore keystore_name.KEYSTORE
  2. Enter keystore password:
  3. sodino_keystore,2010 - 8 - 9, PrivateKeyEntry,
  4. Certified fingerprint (MD5): CB: 5E: F5:33: 23: F4: D2: D3: CC:74: 9D: BF:14: 36: EB: 8D

Under Linux, you can use the openssl command to get:

  1. $ Opensslpkcs7-in CERT.RSA-inform DER-print_certs
  2. subject = / C = US / ST = California / L = Mountain View / O = Android / OU = Android / CN = Android / emailAddress = android@ an   
  3. roid.com
  4. issuer = / C = US / ST = California / L = Mountain View / O = Android / OU = Android / CN = Android / emailAddress = android@ and   
  5. oid.com
  6. ----- BEGIN CERTIFICATE -----
  7. MIIEqDCCA5CgAwIBAgIJALOZgIbQVs/6MA0GCSqGSIb3DQEBBAUAMIGUMQswCQYD
  8. VQQGEwJVUzETMBEGA1UECBMKQ2FsaWZvcm5pYTEWMBQGA1UEBxMNTW91bnRhaW4g
  9. VmlldzEQMA4GA1UEChMHQW5kcm9pZDEQMA4GA1UECxMHQW5kcm9pZDEQMA4GA1UE
  10. AxMHQW5kcm9pZDEiMCAGCSqGSIb3DQEJARYTYW5kcm9pZEBhbmRyb2lkLmNvbTAe
  11. Fw0wODA0MTUyMjQwNTBaFw0zNTA5MDEyMjQwNTBaMIGUMQswCQYDVQQGEwJVUzET
  12. MBEGA1UECBMKQ2FsaWZvcm5pYTEWMBQGA1UEBxMNTW91bnRhaW4gVmlldzEQMA4G
  13. A1UEChMHQW5kcm9pZDEQMA4GA1UECxMHQW5kcm9pZDEQMA4GA1UEAxMHQW5kcm9p
  14. ZDEiMCAGCSqGSIb3DQEJARYTYW5kcm9pZEBhbmRyb2lkLmNvbTCCASAwDQYJKoZI
  15. hvcNAQEBBQADggENADCCAQgCggEBAJx4BZKsDV04HN6qZezIpgBuNkgMbXIHsSAR
  16. vlCGOqvitV0Amt9xRtbyICKAx81Ne9smJDuKgGwms0sTdSOkkmgiSQTcAUk + fArP
  17. GgXIdPabA3tgMJ2QdNJCgOFrrSqHNDYZUer3KkgtCbIEsYdeEqyYwap3PWgAuer9
  18. 5W1Yvtjo2hb5o2AJnDeoNKbf7be2tEoEngeiafzPLFSW8s821k35CjuNjzSjuqtM
  19. 9TNxqydxmzulh1StDFP8FOHbRdUeI0 +76 TybpO35zlQmE1DsU1YHv2mi/0qgfbX3
  20. 6iANCabBtJ4hQC + J7RGQiTqrWpGA8VLoL4WkV1PPX8GQccXuyCcCAQOjgfwwgfkw
  21. HQYDVR0OBBYEFE/koLPdnLop9x1yh8Tnw48ghsKZMIHJBgNVHSMEgcEwgb6AFE/k
  22. oLPdnLop9x1yh8Tnw48ghsKZoYGapIGXMIGUMQswCQYDVQQGEwJVUzETMBEGA1UE
  23. CBMKQ2FsaWZvcm5pYTEWMBQGA1UEBxMNTW91bnRhaW4gVmlldzEQMA4GA1UEChMH
  24. QW5kcm9pZDEQMA4GA1UECxMHQW5kcm9pZDEQMA4GA1UEAxMHQW5kcm9pZDEiMCAG
  25. CSqGSIb3DQEJARYTYW5kcm9pZEBhbmRyb2lkLmNvbYIJALOZgIbQVs/6MAwGA1Ud
  26. EwQFMAMBAf8wDQYJKoZIhvcNAQEEBQADggEBAFclUbjZOh9z3g9tRp + G2tZwFAAp
  27. PIigzXzXeLc9r8wZf6t25iEuVsHHYc/EL9cz3lLFCuCIFM78CjtaGkNGBU2Cnx2C
  28. tCsgSL + ItdFJKe + F9g7dEtctVWV + IuPoXQTIMdYT0Zk4u4mCJH + jISVroS0dao + S
  29. 6h2xw3Mxe6DAN/DRr/ZFrvIkl5 +6 bnoUvAJccbmBOM7z3fwFlhfPJIRc97QNY4L3
  30. J17XOElatuWTG5QhdlxJG3L7aOCA29tYwgKdNHyLMozkPvaosVUz7fvpib1qSN1L
  31. IC7alMarjdW4OZID2q4u1EYjLk/pvZYTlMYwDlE448/Shebk5INTjLixs1c =
  32. ----- END CERTIFICATE -----

The signature 9.apk contrast and instructions


Released Android Application friends should all know Android apk the release is signed.Signature mechanism has a very important role in the Android application framework.

For example, Android system prohibits signature inconsistent APK update installation; If the application requires the use of system permissions, you must ensure that the APK signature Framework signatures consistent, and so on."APK Crack" in an article, we learned to crack a APK necessarily need to re-sign the APK.This signature, in general, can no longer be maintained with the the APK original signature consistent.(Unless the APK the original author's private key leaks, it has another level of software security issues.)

Simply put, the signature mechanism indicated APK issuers.Stood software security point of view, we can through the signature of the APK to determine whether this APK issued by the "official" rather than crack tampered re-sign packaged pirated software.


Android signature mechanism
To illustrate the APK signature than the effectiveness of software security, we need to look at Android apk the signature mechanism.To make it easier to understand, we are talking about a batch command from the Auto-Sign tool.

APK Crack "article, we learned, to sign a signature APK, you can use a tool called Auto-Sign of.Auto-sign tool is actually running is called Sign.bat the batch command.This batch file with a text editor to open, we can find the command to achieve the signature features of this line command:

java-jar signapk.jar testkey.x509.pem testkey.pk8 update.apk update_signed.apk


The significance of this command is: executable jar package through the signapk.jar to testkey.x509.pem this public key file and testkey.pk8 this private key file "update.apk" sign, sign Save the file as "update_signed.apk".
For private and public keys are generated here, here do not further described.This information we can find a lot. We are here to talk about the the signapk.jar in the end what has been done.

signapk.jar the Android source package signature tool. Since Android is an open source project, so glad we can find source code of signapk.jar!Path / build / tools / signapk / SignApk.java.

Contrast without a signed APK and a good signature APK, we will find more good signature APK package called META-INF folder.There are three files, and namely the MANIFEST.MF, CERT.SF and CERT.RSA.signapk.jar is to generate these documents (other documents without any change, so we can easily remove the original signature information).

By reading signapk source, we can sort out the whole process of signing APK package.

1 to generate the MANIFEST.MF file:

Program the traversal update.apk package all the files (entry), carried out one by one to generate SHA1 digital signature information, and then Base64 encoded the non folder signature file file.Specific code to see this method:

private static Manifest addDigestsToManifest (JarFile jar)


The key code is as follows:

1 for (JarEntry entry: byName.values ??()) {
2 String name = entry.getName ();
3 if (! Entry.isDirectory () &&! Name.equals (JarFile.MANIFEST_NAME) &&
4! Name.equals (CERT_SF_NAME) &&! Name.equals (CERT_RSA_NAME) &&
5 (stripPattern == null | |! StripPattern.matcher (name). Matches ())) {
6 InputStream data = jar.getInputStream (entry);
While ((at num = data.read (buffer))> 0) {
8 md.update (buffer, 0, num);
9}
10 Attributes attr = null;
11 if (input! = Null) the attr = input.getAttributes (name);
12 attr = attr! = Null? New Attributes (attr): new Attributes ();
13 attr.putValue ("SHA1-Digest", base64.encode (md.digest ()));
14 output.getEntries (). Put (name, attr);
15}
16}

After the resulting signed written to the MANIFEST.MF file.The key code is as follows:

1 Manifest manifest = addDigestsToManifest (inputJar);
2 je = new JarEntry (JarFile.MANIFEST_NAME);
3 je.setTime (timestamp);
4 outputJar.putNextEntry (je);
5 manifest.write (outputJar);
Here briefly under SHA1 digital signature. Simply put, it is a secure hash algorithm, similar to the MD5 algorithm.The input of any length into a fixed-length output hash algorithm (here called "Summary Information").You can not only through this summary information to recover the original information.In addition, it guarantees a summary of the information is different from each other.So if you change the file in the apk package, then apk installation check the changed file summary information with MANIFEST.MF inspection information, so the program can not be successfully installed.


2 generate CERT.SF file:

On the the generated MANIFEST in the previous step, use the SHA1-RSA algorithm, to be signed with the private key.The key code is as follows:

1 Signature signature = Signature.getInstance ("SHA1withRSA");
2 signature.initSign (privateKey);
3 je = new JarEntry (CERT_SF_NAME);
4 je.setTime (timestamp);
5 outputJar.putNextEntry (je);
6 writeSignatureFile (the manifest,
7 new SignatureOutputStream (outputJar, signature));
RSA is an asymmetric encryption algorithm. Summary information is encrypted by using the private key RSA algorithm.Install only with the public key can decrypt it. Decryption summary information unencrypted contrast, if there is a match, it indicates that the content is not unusual modifications.


3 generate CERT.RSA file:

The generated MANIFEST.MF no key information, generate CERT.SF file using the private key file.Then we can easily guess, CERT.RSA file generation is certainly relevant and the public key.

CERT.RSA file saved public key encryption algorithm. The core code is as follows:

1 je = new JarEntry (CERT_RSA_NAME);
2 je.setTime (timestamp);
3 outputJar.putNextEntry (JE);
4 writeSignatureBlock (signature, publicKey, outputJar);
Which code of writeSignatureBlock is as follows:

1 the private static void writeSignatureBlock of (
2 Signature signature, X509Certificate publicKey, OutputStream out)
3 throws IOException, GeneralSecurityException {
4 SignerInfo signerInfo = new SignerInfo (
5 new X500Name (publicKey.getIssuerX500Principal (). GetName ()),
6 publicKey.getSerialNumber (),
7 AlgorithmId.get ("SHA1"),
8 AlgorithmId.get ("RSA"),
9 signature.sign ());
10
11 PKCS7 pkcs7 = newPKCS7 (
12 new AlgorithmId [] in {AlgorithmId.get (SHA1)},
13 new ContentInfo (ContentInfo.DATA_OID, null),
14 new X509Certificate [] {publicKey},
15 new SignerInfo [] {signerInfo});
16
17 pkcs7.encodeSignedData (out);
18}


The, analyzing the APK package signature process, we can be aware of:

The Android signature mechanism is actually only a checking mechanism of the APK package integrity and the issuing agency.

The Android signature mechanism can not prevent the APK package is modified, but the modified re-signature can not be consistent with the original signature.(With private key in exceptional circumstances).

The 3, APK packet encryption public key packaged in the APK package, and the type of the private key corresponding to the type of the public key.In other words words, the APK public key signed with the private I will not be the same.So that we can be based on public key comparison to determine the private key are the same.


APK signature than on the way to achieve this:
Well, the Android signature mechanism analysis, we proved theoretically that a through the APK public key than can judge an APK issuing agency.And the release mechanism is difficult to fake, we do that can not be disguised.

Theoretical basis, we can begin to practice. So how to obtain the public key information to the APK file?Because Android system installer will certainly get the APK information for comparison, so we can get some ideas and help through the Android source code.

Source in a hidden class is used to resolve APK package.This class is called PackageParser path for frameworks \ base \ core \ java \ android \ content \ pm \ PackageParser.java.When we need to obtain a the APK package of information, you can directly use this class, the following code is an example of a function:

1 private PackageInfo parsePackage (String archiveFilePath, int flags) {
2
3 PackageParser packageParser = new PackageParser (archiveFilePath);
4 of DisplayMetrics metrics to = new DisplayMetrics ();
5 metrics.setToDefaults ();
6 final File sourceFile = new File (archiveFilePath);
7 PackageParser.Package pkg = packageParser.parsePackage (
8 sourceFile, archiveFilePath, metrics, 0);
9 if (pkg == null) {
10 return null;
11}
12
13 packageParser.collectCertificates the (pkg 0);
14
15 return PackageParser.generatePackageInfo (pkg, null, flags, 0, 0);
16}
Parameters archiveFilePath specified the APK file path; the flags need set PackageManager.GET_SIGNATURES bit, to ensure that the certificate signature information.

The specific PackageParser for signature information not detailed here, the specific code reference PackageParser the public boolean collectCertificates (Package pkg, int flags) and private Certificate [] loadCertificates (JarFile to jarFile JarEntry for the je, byte [] readBuffer) Methods. As for how to hide classes and methods used in Android application development can be found in my article: "Android application developers how to use hidden APIs."

Then, we can by packageInfo.signatures to access to the the APK signature information.Also should be noted that the correspondence between Android of Signature and Java in Certificate.Their relationship as shown in the following code:

1 pkg.mSignatures = new Signature [certs.length];
2 for (int i = 0; i <N; i + +) {
3 pkg.mSignatures [i] = new Signature (
4 certs [i]. GetEncoded ());
5}
That signature = new Signature (certificate.getEncoded, ()); Certificate certificate contains a public key and certificate other basic information.Different public key certificate is definitely different from each other.We can certificate getPublicKey method to obtain the public key information.Than-signed certificate is essentially public key information.

OK, get to APK-signed certificate on the left than the right.This simple, function as follows:

1 private boolean IsSignaturesSame (Signature [] s1, Signature [] s2) {
If (s1 == null) {
Return false;
4}
If (s2 == null) {
Return false;
7}
8 HashSet <Signature> set1 = new HashSet <Signature> ();
9 for (Signature sig: s1) {
10 set1.add (sig);
11}
12 HashSet <Signature> set2 = new HashSet <Signature> ();
13 for (Signature sig: s2) {
14 set2.add (sig);
15}
16 / / Make sure s2 contains all signatures in s1.
17 the if (set1.equals (SET2)) {
18 return true;
19}
20 return false;
21}

APK signature comparison scenarios

After the above discussion, surely we have learned signature than on the principles and implementation.So what when suitable for use the signature contrast to protect the Android apk's software security?

Personally think mainly the following three scenarios:

1, the program is self-test. When the program is running, self-signature comparison.Than the samples can be stored the APK package can also be stored in the cloud.The disadvantage is that the program to crack, since the detection function may be destroyed, so that it no longer.

2, the reliable third-party testing. APK software by a trusted third-party program is responsible for security issues.The comparison samples collected by a third party in the cloud. This approach applies to the anti-virus security software or APP Market software download market.The disadvantage is the need networking detection function can not be achieved in the case of no network.(It is impossible to put a lot of signature data on mobile devices local).

3, the system is limited to installation. This relates to the change Android system.Limited to only install the apk of some certificates. Software publishers will need to be posted on the application for a certificate to the system.If problems are found, can be traced to which software publisher's responsibility.Applied to the system provider or end-product manufacturers. The disadvantage is too closed, is not conducive to the openness of the system.

All scenarios have their own shortcomings, but the disadvantage is not can not be overcome.For example, we can consider the program from the detection method of implementation of the native method.Software security is a complex issue, which often requires a variety of techniques used in combination in order to better protect the software does not vandalism.

0 0
原创粉丝点击