在应用程序中隐藏敏感数据

Hide sensitive data inside application

我正在使用改造请求:

@Headers("Authorization: Basic: UsernamePassword")
@POST("services/2/something/something")
fun createPlan(@Body planData: PlanInfo): Call<Plan>

在我的 header 中,我要求以 Base64 编码发送用户名和密码以及字符串。但如果反编译应用程序,解码并不难。 所以我参考了手册:https://medium.com/novumlogic/hiding-sensitive-data-in-android-app-dbd64e88224f 在 android app.

中隐藏敏感数据

但是现在当我像这样使用来自常量的数据时:

@Headers("Authorization: "+ConstantsEncrypted.usernamePassword())
@POST("services/2/something/something")
fun createPlan(@Body planData: PlanInfo): Call<Plan>

我收到错误消息:注释参数必须是 compile-time 常量。

那么如何正确隐藏这些敏感数据呢?

您不能使用注释方法来做到这一点。以下是我在项目中的做法。

class Authenticator : Authenticator {

    override fun authenticate(route: Route?, response: Response): Request? {

        return response.request().newBuilder()
            .header("Authorization", ConstantsEncrypted.usernamePassword()).build()
    }

}

并且不要忘记使用 authenticator(Authenticator()) 将其添加到您的 OkHttpClient.Builder() 实例,如下所示:

OkHttpClient.Builder().apply {
    writeTimeout(120, TimeUnit.SECONDS)
    readTimeout(120, TimeUnit.SECONDS)
    connectTimeout(120, TimeUnit.SECONDS)
    callTimeout(120, TimeUnit.SECONDS)
    // your code
    // this is where you add your authenticator
    authenticator(Authenticator())
    // more code 
}.build()

Authenticator 来自程序包 okhttp3。您可以在 class here.

上找到更多信息

找到解决方案,发送header到函数:

fun createPlan(@HeaderMap headers: Map<String, String>,@Body planData: PlanInfo): Call<Plan>