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")
        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)
} catch (e: NoSuchAlgorithmException) {