Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save chinalwb/d546334ee8c5ba7afbad8a79d1e6a70f to your computer and use it in GitHub Desktop.
Save chinalwb/d546334ee8c5ba7afbad8a79d1e6a70f to your computer and use it in GitHub Desktop.
Android get App SHA256 fingerprint
/**
* Get SHA256 from PackageManager / PackageInfo / Signatures
*/
fun printSignature() {
val packageManager: PackageManager = CONTEXT.getPackageManager()
val signature: Array<Signature> = packageManager.getPackageInfo("YOUR PACKAGE_NAME, LIKE com.xx.yy.zz", PackageManager.GET_SIGNATURES).signatures
signature.asIterable().forEach {
Log.i("SHA256", getFingerprint(it))
}
}
/**
* Get fingerprint from a certificate in android.content.pm.Signature
* @return String fingerprint that contains the SHA-256 digest
*/
private fun getFingerprint(ce: Signature): String? {
var certificate = ""
val input: InputStream = ByteArrayInputStream(ce.toByteArray())
var cf: CertificateFactory? = null
try {
cf = CertificateFactory.getInstance("X509")
} catch (e: CertificateException) {
e.printStackTrace()
}
var c: X509Certificate? = null
try {
if (cf != null) {
c = cf.generateCertificate(input) as X509Certificate
}
} catch (e: CertificateException) {
e.printStackTrace()
}
try {
val md: MessageDigest = MessageDigest.getInstance("SHA-256")
var publicKey = ByteArray(0)
if (c != null) {
publicKey = md.digest(c.encoded)
}
val hexString = StringBuilder()
for (aPublicKeybyte in publicKey) {
val appendString = Integer.toHexString(0xFF and aPublicKeybyte.toInt())
if (appendString.length == 1) hexString.append("0")
hexString.append(appendString)
}
certificate = hexString.toString()
} catch (e1: NoSuchAlgorithmException) {
e1.printStackTrace()
} catch (e1: CertificateEncodingException) {
e1.printStackTrace()
}
return certificate
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment