Complete legality of executable files in Android operation

Source: Internet
Author: User
Tags md5 digest

I. Overviewbecause the previous project has a dynamic hot fix feature, the repair process will download a new Dex file from the server to replace the old Dex file, so it involves the issue of file identity validation. Usually the interface will be issued a MD5 value, only a MD5 value of the words can only do a integrity check, It is not possible to determine the legitimacy of the file, and if the attacker has issued a correct MD5 value for the interface, the file can still be replaced. So here is the validation MD5 integrity after the validity of the signature to do the validation.Two. Implement

1. File Integrity Validation

Here the string takes MD5 to do not repeat. Since the integrity of the file is to be tested, it is involved in fetching the file MD5 Digest, which is used by the messagedigest in the JDK to read the file binary stream, The MD5 summary of the file stream is updated with update cumulative to get a MD5 summary of the entire file. After getting the file MD5, the comparison with the interface is OK. So it's simple to do file integrity validation.

    /**     * Get file MD5 *     @param file     * @return *     @throws nosuchalgorithmexception     * @throws ioexception< c6/>*/    private static String getFileMD5 (file file) throws NoSuchAlgorithmException, IOException {        if (! File.isfile ()) {            return null;        }        MessageDigest Digest;        FileInputStream in;        byte buffer[] = new byte[1024];        int Len;        Digest = messagedigest.getinstance ("MD5");        in = new FileInputStream (file);        while (len = in.read (buffer, 0, 1024x768)! =-1) {            digest.update (buffer, 0, Len);        }        In.close ();        BigInteger bigInt = new BigInteger (1, Digest.digest ());        return bigint.tostring (+);    }
2. Validity of documents

The validity of the document is more complex than the integrity of the validation, where the legitimacy is based on the signature to do, so at least a simple understanding of the signature process, the signature after the file changes and how to obtain the document signature information.
1) post-signature output

The process of generating signature files and signatures There is no detail here, the main analysis after the signature of some of the situation. After extracting the signature files can be seen through the signature generated a Meta-inf folder, which is generally three files used to store all the files of the validation and signature information.


MANIFEST. MF: BASE64 hashes can be viewed in clear text for all files.


androidk. SF: BASE64 hashes can be viewed in clear text for the first three rows of all files.


androidk. RSA: The first two files are just a hash summary of the file, and there is no signature of the public key information, RSA file contains the information we need, which contains the developer information, The developer's public key and the secret of the CA based on the summary information of the first two files after the private key is encrypted. RSA files are not viewable in plaintext, and you can use the OpenSSL command to output the file's information. OpenSSL pkcs7-inform der-in androidk. Rsa-noout-print_certs-text, from the data structure of this file, this chapter needs to use the public key, get the file's own certificate information of the public key, and then compare the app's own signature public key to determine the legitimacy of the file.


2) Get the app's own signature

through the above introduction can be learned that the signed file can be obtained by an RSA RSA public key, which is validated by the way to verify the legitimacy of the key, the app's own signature information can be obtained through PackageInfo, After getting to the string conversion and interception, the RSA public key is extracted out of the OK.

    /** * Get local app RSA public key * @param CTX * @return * @throws IOException * @throws Packagem Anager. Namenotfoundexception * @throws certificateexception */private static String Getlocalsignature (Context ctx) th        Rows IOException, Packagemanager.namenotfoundexception, certificateexception {String signcode = null; Get signature info depends on package name PackageInfo PackageInfo = Ctx.getpackagemanager (). Getpackageinfo        (Ctx.getpackagename (), packagemanager.get_signatures);        Signature[] signs = packageinfo.signatures;        Signature sign = signs[0];        Certificatefactory certfactory = certificatefactory. getinstance ("the"); X509Certificate cert = (x509certificate) certfactory. Generatecertificate (New Bytearrayinputstream (Sign.toB        Ytearray ()));        String PubKey = Cert.getpublickey (). toString ();        String ss = Subpublicsignature (PubKey);SS = Ss.replace (",", "");        SS = Ss.tolowercase ();        int aa = Ss.indexof ("modulus");        int bb = ss.indexof ("publicexponent");        signcode = ss.substring (aa + 8, BB);    return signcode; }
3) Get External file signature
the process of obtaining an external file signature can actually refer to the Android internal validation apk file process, the Android source Packageparser class will be installed APK file before installing the validity of the apk files, But unfortunately this class is labeled hide, so we can't use it directly. Then there are only two methods left, one is through reflection using Packageparser method, a look at the source of the implementation of this part of the realization and then pull out of their own implementation.

/** * Package Archive parsing * * {@hide} */public class Packageparser {    //source/frameworks/base/core/java/android/c ONTENT/PM}
It is not recommended to use reflection in the current usage scenario, one is to use reflection to reduce efficiency and risk, and the other is that it does not rely on other parts of Android, but relies on the jarfile in the JDK. So the deduction source of their own implementation came more real, This does not analyze the use of reflection verification process, directly on the source code.

The following code snippet can be seen from the Collectcertificates method in the Packageparser class. First load the signed Apk,jar or zip file into jarfile based on the file path ( Jarfile is inherited from ZipFile), and then gets a file in the Content Department of the file (this part of the code block is the manifest file obtained), and then obtains the certificate information to the file. As long as you can get the certificate information, then get the public key or something is a small case.

    public boolean collectcertificates (package pkg, int flags) {        //...        .... Jarfile jarfile = new Jarfile (marchivesourcepath);        //.................        Jarentry jarentry = Jarfile.getjarentry (android_manifest_filename);        //.................        Certs = Loadcertificates (Jarfile, Jarentry, readbuffer);        Pkg.msignatures = null;        //.................    }
this loadcertificates method needs special mention, because at the beginning I was reading the source after the implementation of their own, look at this method when each note, read the file stream did not do anything to skip the steps, Obtain a certificate directly from Jarentry.getcertificates. The results changed several signed files can not get the certificate, re-read the next source to find the note must use Jarentry read the file stream to receive the certificate information ... If you don't die, you will not die. After you get the certificate, just like the steps in the previous 2), get the public key directly, and then intercept the string to truncate the RSA common key, and the result in the last 2) can be done in a legitimate way.

    private static certificate[] Loadcertificates (jarfile jarfile, Jarentry je,                                                  byte[] readbuffer) throws IOException { c4/>//We must read the stream for the Jarentry-retrieve        //its certificates.        InputStream is = new Bufferedinputstream (Jarfile.getinputstream (JE));        while (Is.read (readbuffer, 0, readbuffer.length)! =-1) {            //not using        }        is.close ();        Return JE! = null? Je.getcertificates (): null;    }


Reprint Please specify Source:http://blog.csdn.net/l2show/article/details/48182367

Complete legality of executable files in Android operation

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.