简体   繁体   中英

How do I generate SHA512 checksum for an Android Apk file on android studio

I need to generate a checksum for a downloaded apk file and make a comparison with another checksum sent when downloading the apk. This will have to be done in android studio.

You are basically asking to calculate the SHA-512 of a file, it doesn't matter what type of file it is: apk, zip, exe...

There is a lot of information about calculating different hashes on Android. In order to filter through the answers, I think you could consider the size of the APK files. It doesn't really matter what hash you want to calculate, as the only thing that changes is probably just one line:

    MessageDigest.getInstance("MD5")
    MessageDigest.getInstance("SHA1")
    MessageDigest.getInstance("SHA-256")
    MessageDigest.getInstance("SHA-512")

For example, if the APKs are very heavy, you can check this out: How to calculate hash value of a file in Java?

This one is great because works with chunks, so there's no need to load the whole file into memory.

Then, once you have both hashes calculated, you can convert them to Base64 in order to compare them as regular String .

The previous answer did work, but with a lot of code. Found an easy way using apache commons.

Add apache commons to build gradle

implementation group: 'commons-codec', name: 'commons-codec', version: '1.12'
private fun checksum(destination: String) {
        try {
            val array = Files.readAllBytes(Paths.get(destination))
            val genchecksum = DigestUtils.sha512Hex(array)

            apkChecksum = genchecksum.toString()

        } catch (e: Exception) {
            Log.e(javaClass.simpleName, "File error", e)
        }
    }

Note -- The destination is the path of the file with the file name

Sample

var destination = context.getExternalFilesDir(Environment.DIRECTORY_DOWNLOADS).toString()/filename.apk

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM