SMS Retriever API: Computing your app’s hash

You can find info on what the SMS Retriever API is here. Chances are that reaching this page means you already know that. For some reasons the hash generation process described in the docs did not work for me. Probably it’s a Mac only issue or the implementation of the sha256sum function I installed with coreutils.

What worked for me is getting the hash from within the App. A helper class for this is provided in Google Samples project.

A Kotlin snippet that does the same can be found bellow.

fun getAppSignature(context: Context) = context.packageManager.getPackageInfo(context.packageName, PackageManager.GET_SIGNATURES)
        .signatures.mapNotNull { hash(context.packageName, it.toCharsString()) }.firstOrNull()

private fun hash(packageName: String, signature: String) = try {
    val messageDigest = MessageDigest.getInstance("SHA-256")
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
        messageDigest.update("$packageName $signature".toByteArray(StandardCharsets.UTF_8))
    }
    var hashSignature = messageDigest.digest()
    hashSignature = Arrays.copyOfRange(hashSignature, 0, 9)
    var base64Hash = Base64.encodeToString(hashSignature, Base64.NO_PADDING or Base64.NO_WRAP)
    base64Hash = base64Hash.substring(0, 11)
    base64Hash
} catch (e: NoSuchAlgorithmException) {
    null
}
Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

This site uses Akismet to reduce spam. Learn how your comment data is processed.