Verify OTP Without SMS Permission In Android Using Kotlin

Introduction

Google has updated the policy in Google Developer Blog about user privacy and security. As per the policy, we must remove SMS and Call Log permissions from manifest or else our app will be removed from the Google play store. But our app needs SMS permission for automatically authenticating app users. What is the solution?
Google offers an API named SMS Retriever API to allow our app to read SMS without SMS permission and we need to follow a set of rules while formatting the verification message. In this article, we will learn how to use SMS Retriever API in Kotlin to read SMS and rules need to be followed. If you are new to Kotlin, read my previous articles to read Kotlin from scratch.

Verification Message Format

We should follow the below rules while formatting verification message.
  1. A message should have a maximum of 140 bytes length.
  2. Should start with “<#>”.
  3. Followed by OTP - One Time Pass (code/word).
  4. 11 character length hash for the app (it is generated by our app).
Example
  1. <#> Your Example App code is: 123ABC78
  2. FA+9qCX9VSu

Coding Part

I have detailed the article as in the following steps.
  • Step 1: Creating a New Project with Empty Activity.
  • Step 2: Setting up the Google Auth Libraries.
  • Step 3: Implementation of SMS Retriever API using Kotlin.
Step 1 - Creating a new project with Kotlin
  1. Open Android Studio and select "Create new project".
  2. Name the project as your wish and tick the Kotlin Support checkbox.
  3. Then Select your Activity type (For example, Navigation Drawer Activity, Empty Activity, etc.).

    Verify OTP Without SMS Permission In Android Using Kotlin

  4. Then, click the “Finish” button to create a new project in Android Studio.
Step 2 - Setting up the Google Auth Libraries
In this part, we will see how to set up the library for the project.
  1. Then add the following lines in app level build.gradle file to apply Google services to your project.
    1. dependencies {
    2. …
    3. implementation 'com.google.android.gms:play-services-base:11.6.0'
    4. implementation 'com.google.android.gms:play-services-auth-api-phone:11.6.0'
    5. …
    6. }
  1. Then click “Sync Now” to setup your project.
  2. Now the project is ready and no need to add any permissions in Manifest.
Step 3 - Implementation of SMS Retriever API using Kotlin
  • Create a user interface to display your OTP read through the API. Open or create “activity_main.xml” and paste the following code snippet.
    1. <?xml version="1.0" encoding="utf-8"?>
    2. <android.support.constraint.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    3. xmlns:app="http://schemas.android.com/apk/res-auto"
    4. xmlns:tools="http://schemas.android.com/tools"
    5. android:layout_width="match_parent"
    6. android:layout_height="match_parent"
    7. tools:context="com.androidmad.smsretrieverapisample.MainActivity">
    8. <EditText
    9. android:id="@+id/editText"
    10. android:layout_width="match_parent"
    11. android:layout_height="wrap_content"
    12. android:layout_marginLeft="20dp"
    13. android:layout_marginRight="20dp"
    14. app:layout_constraintBottom_toBottomOf="parent"
    15. app:layout_constraintLeft_toLeftOf="parent"
    16. app:layout_constraintRight_toRightOf="parent"
    17. app:layout_constraintTop_toTopOf="parent" />
    18. <Button
    19. android:onClick="onBtnResendClick"
    20. android:id="@+id/btn_restart"
    21. android:text="Resend"
    22. android:layout_width="0dp"
    23. android:layout_height="wrap_content"
    24. android:layout_marginLeft="20dp"
    25. android:layout_marginRight="20dp"
    26. app:layout_constraintBottom_toBottomOf="parent"
    27. app:layout_constraintEnd_toEndOf="parent"
    28. app:layout_constraintHorizontal_bias="0.0"
    29. app:layout_constraintLeft_toLeftOf="parent"
    30. app:layout_constraintRight_toRightOf="parent"
    31. app:layout_constraintStart_toStartOf="parent"
    32. app:layout_constraintTop_toTopOf="@id/editText"
    33. app:layout_constraintVertical_bias="0.247" />
    34. </android.support.constraint.ConstraintLayout>
  • We need to create a helper class to provide the hash value for our app to construct the verification message. Create a Kotlin class file named as “AppSignatureHelper.kt” and paste the following code snippet which is helpful to create an 11 character length hash for our application.
    1. package com.androidmad.smsretrieverapisample
    2. import android.annotation.SuppressLint
    3. import android.content.Context
    4. import android.content.ContextWrapper
    5. import android.content.pm.PackageManager
    6. import android.os.Build
    7. import android.support.annotation.RequiresApi
    8. import android.util.Base64
    9. import android.util.Log
    10. import java.nio.charset.StandardCharsets
    11. import java.security.MessageDigest
    12. import java.security.NoSuchAlgorithmException
    13. import java.util.*
    14. class AppSignatureHelper(context: Context) : ContextWrapper(context) {
    15. /**
    16. * Get all the app signatures for the current package
    17. *
    18. * @return
    19. */
    20. // Get all package signatures for the current package
    21. // For each signature create a compatible hash
    22. val appSignatures: ArrayList<String>
    23. @SuppressLint("PackageManagerGetSignatures")
    24. @RequiresApi(api = Build.VERSION_CODES.KITKAT)
    25. get() {
    26. val appCodes = ArrayList<String>()
    27. try {
    28. val packageName = packageName
    29. val packageManager = packageManager
    30. val signatures = packageManager.getPackageInfo(packageName,
    31. PackageManager.GET_SIGNATURES).signatures
    32. signatures
    33. .mapNotNull { hash(packageName, it.toCharsString()) }
    34. .mapTo(appCodes) { String.format("%s", it) }
    35. } catch (e: PackageManager.NameNotFoundException) {
    36. Log.v(TAG, "Unable to find package to obtain hash.", e)
    37. }
    38. return appCodes
    39. }
    40. companion object {
    41. val TAG = AppSignatureHelper::class.java.simpleName!!
    42. private val HASH_TYPE = "SHA-256"
    43. private val NUM_HASHED_BYTES = 9
    44. private val NUM_BASE64_CHAR = 11
    45. @RequiresApi(api = Build.VERSION_CODES.KITKAT)
    46. private fun hash(packageName: String, signature: String): String? {
    47. val appInfo = packageName + " " + signature
    48. try {
    49. val messageDigest = MessageDigest.getInstance(HASH_TYPE)
    50. messageDigest.update(appInfo.toByteArray(StandardCharsets.UTF_8))
    51. var hashSignature = messageDigest.digest()
    52. // truncated into NUM_HASHED_BYTES
    53. hashSignature = Arrays.copyOfRange(hashSignature, 0, NUM_HASHED_BYTES)
    54. // encode into Base64
    55. var base64Hash = Base64.encodeToString(hashSignature, Base64.NO_PADDING or Base64.NO_WRAP)
    56. base64Hash = base64Hash.substring(0, NUM_BASE64_CHAR)
    57. Log.v(TAG + "sms_sample_test", String.format("pkg: %s -- hash: %s", packageName, base64Hash))
    58. return base64Hash
    59. } catch (e: NoSuchAlgorithmException) {
    60. Log.v(TAG + "sms_sample_test", "hash:NoSuchAlgorithm", e)
    61. }
    62. return null
    63. }
    64. }
    65. }
  • Then, we need to get the hash from the class by creating an object for the helper class and calling the hash creation method which returns the value.
    1. // This code requires one time to get Hash keys do comment and share key
    2. val appSignature = AppSignatureHelper(this)
    3. Log.v("AppSignature", appSignature.appSignatures.toString())
  • Create a Custom BroadCastReceiver class named as “MySMSBroadcastReceiver.kt” and add the following code snippets.
    1. class MySMSBroadcastReceiver : BroadcastReceiver() {
    2. private var otpReceiver: OTPReceiveListener? = null
    3. fun initOTPListener(receiver: OTPReceiveListener) {
    4. this.otpReceiver = receiver
    5. }
    6. override fun onReceive(context: Context, intent: Intent) {
    7. if (SmsRetriever.SMS_RETRIEVED_ACTION == intent.action) {
    8. val extras = intent.extras
    9. val status = extras!!.get(SmsRetriever.EXTRA_STATUS) as Status
    10. when (status.statusCode) {
    11. CommonStatusCodes.SUCCESS -> {
    12. // Get SMS message contents
    13. var otp: String = extras.get(SmsRetriever.EXTRA_SMS_MESSAGE) as String
    14. Log.d("OTP_Message", otp)
    15. // Extract one-time code from the message and complete verification
    16. // by sending the code back to your server for SMS authenticity.
    17. // But here we are just passing it to MainActivity
    18. if (otpReceiver != null) {
    19. otp = otp.replace("<#> ", "").split("\n".toRegex()).dropLastWhile { it.isEmpty() }.toTypedArray()[0]
    20. otpReceiver!!.onOTPReceived(otp)
    21. }
    22. }
    23. CommonStatusCodes.TIMEOUT ->
    24. // Waiting for SMS timed out (5 minutes)
    25. // Handle the error ...
    26. if (otpReceiver != null)
    27. otpReceiver!!.onOTPTimeOut()
    28. }
    29. }
    30. }
    31. interface OTPReceiveListener {
    32. fun onOTPReceived(otp: String)
    33. fun onOTPTimeOut()
    34. }
    35. }
  • Here, OTPReceiveListener is an interface used to call back the events from broad cast receiver. Then open your Activity and implement OTPReceiverListener.

  • Register the receiver in AndroidManifest.xml with SMS_RETRIEVED action.
    1. <receiver android:name=".MySMSBroadcastReceiver" android:exported="true">
    2. <intent-filter>
    3. <action android:name="com.google.android.gms.auth.api.phone.SMS_RETRIEVED" />
    4. </intent-filter>
    5. </receiver>
  • Then, start the SmsRetriever API as shown in below. Also, register your broadcast receiver with SmsRetriever.SMS_RETRIEVED_ACTION using intent filter.
    1. private fun startSMSListener() {
    2. try {
    3. smsReceiver = MySMSBroadcastReceiver()
    4. smsReceiver!!.initOTPListener(this)
    5. val intentFilter = IntentFilter()
    6. intentFilter.addAction(SmsRetriever.SMS_RETRIEVED_ACTION)
    7. this.registerReceiver(smsReceiver, intentFilter)
    8. val client = SmsRetriever.getClient(this)
    9. val task = client.startSmsRetriever()
    10. task.addOnSuccessListener {
    11. // API successfully started
    12. }
    13. task.addOnFailureListener {
    14. // Fail to start API
    15. }
    16. } catch (e: Exception) {
    17. e.printStackTrace()
    18. }
    19. }

You will receive the OTP in call back methods implemented in your Activity.

  1. override fun onOTPReceived(otp: String) {
  2. //showToast("OTP Received: " + otp)
  3. editText.setText(otp)
  4. if (smsReceiver != null) {
  5. LocalBroadcastManager.getInstance(this).unregisterReceiver(smsReceiver)
  6. }
  7. }
  8. override fun onOTPTimeOut() {
  9. showToast("OTP Time out")
  10. }

Full Code

You can find the full code implementation of the Activity here.
  1. class MainActivity : AppCompatActivity(), OTPReceiveListener {
  2. private var smsReceiver: MySMSBroadcastReceiver? = null
  3. override fun onCreate(savedInstanceState: Bundle?) {
  4. super.onCreate(savedInstanceState)
  5. setContentView(R.layout.activity_main)
  6. startSMSListener()
  7. }
  8. /**
  9. * Starts SmsRetriever, which waits for ONE matching SMS message until timeout
  10. * (5 minutes). The matching SMS message will be sent via a Broadcast Intent with
  11. * action SmsRetriever#SMS_RETRIEVED_ACTION.
  12. */
  13. private fun startSMSListener() {
  14. try {
  15. smsReceiver = MySMSBroadcastReceiver()
  16. smsReceiver!!.initOTPListener(this)
  17. val intentFilter = IntentFilter()
  18. intentFilter.addAction(SmsRetriever.SMS_RETRIEVED_ACTION)
  19. this.registerReceiver(smsReceiver, intentFilter)
  20. val client = SmsRetriever.getClient(this)
  21. val task = client.startSmsRetriever()
  22. task.addOnSuccessListener {
  23. // API successfully started
  24. }
  25. task.addOnFailureListener {
  26. // Fail to start API
  27. }
  28. } catch (e: Exception) {
  29. e.printStackTrace()
  30. }
  31. }
  32. fun onBtnResendClick(view: View){
  33. startSMSListener()
  34. }
  35. override fun onOTPReceived(otp: String) {
  36. //showToast("OTP Received: " + otp)
  37. editText.setText(otp)
  38. if (smsReceiver != null) {
  39. LocalBroadcastManager.getInstance(this).unregisterReceiver(smsReceiver)
  40. }
  41. }
  42. override fun onOTPTimeOut() {
  43. showToast("OTP Time out")
  44. }
  45. override fun onDestroy() {
  46. super.onDestroy()
  47. if (smsReceiver != null) {
  48. LocalBroadcastManager.getInstance(this).unregisterReceiver(smsReceiver)
  49. }
  50. }
  51. private fun showToast(msg: String) {
  52. Toast.makeText(this, msg, Toast.LENGTH_SHORT).show()
  53. }
  54. }
Reference
SMS Retriever API for Android
https://developers.google.com/identity/sms-retriever/overview
Google Announcement on Security Policy
https://android-developers.googleblog.com/2019/01/reminder-smscall-log-policy-changes.html
If you have any doubts or need any help, contact me.
Download Code
You can download the full source code of the article in GitHub. If you like this article, do star the repo on GitHub.