Skip to content

Instantly share code, notes, and snippets.

@itszechs
Created April 4, 2022 16:09
Show Gist options
  • Select an option

  • Save itszechs/8e2918654ce8e55b1c564bda1d796774 to your computer and use it in GitHub Desktop.

Select an option

Save itszechs/8e2918654ce8e55b1c564bda1d796774 to your computer and use it in GitHub Desktop.
Retrieve android app's signature programmatically
import android.content.Context
import android.content.pm.PackageManager
import android.util.Log
import java.security.MessageDigest
import java.security.NoSuchAlgorithmException
object AppSignature {
@Suppress("unused")
enum class Hash {
SHA1, SHA256, MD5
}
fun get(context: Context, hash: Hash): String? {
try {
val signatures = with(context.packageManager) {
getPackageInfo(
context.packageName,
PackageManager.GET_SIGNING_CERTIFICATES
).signingInfo.apkContentsSigners
}
for (signature in signatures) {
val md = MessageDigest.getInstance(hash.name)
md.update(signature.toByteArray())
val digest = md.digest()
val toRet = StringBuilder()
digest.indices.forEach {
if (it != 0) toRet.append(":")
val b = digest[it].toInt() and 0xff
val hex = Integer.toHexString(b)
if (hex.length == 1) toRet.append("0")
toRet.append(hex.uppercase())
}
Log.d("AppSignature", "$hash.name $toRet")
return toRet.toString()
}
} catch (e1: PackageManager.NameNotFoundException) {
Log.d("AppSignature", e1.toString())
} catch (e: NoSuchAlgorithmException) {
Log.d("AppSignature", e.toString())
} catch (e: Exception) {
Log.d("AppSignature", e.toString())
}
return null
}
}
@faizul726
Copy link

Thank you. I have started using it in app and it works great

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment