package com.sentinelshield.mobile.deviceowner

data class EnterpriseWipeAuthorization(
    val commandId: String,
    val confirmationDigest: String,
    val issuedAtEpochMillis: Long,
    val expiresAtEpochMillis: Long,
) {
    fun isValid(nowEpochMillis: Long, expectedDigest: String): Boolean =
        commandId.isNotBlank() &&
            nowEpochMillis in issuedAtEpochMillis..expiresAtEpochMillis &&
            constantTimeEquals(confirmationDigest, expectedDigest)

    private fun constantTimeEquals(left: String, right: String): Boolean {
        if (left.length != right.length) return false
        var difference = 0
        for (index in left.indices) {
            difference = difference or (left[index].code xor right[index].code)
        }
        return difference == 0
    }
}
