我正在调查com.google.crypto.tink:tink-android:1.6.1
在我当前的 Android 项目中的使用。
我正在加密的数据包括我用于远程 API 调用的 OAuth2 访问令牌/刷新令牌,例如,访问令牌是我的授权 HTTP 标头的承载令牌。
我担心我的加密/解密逻辑出错,因为我遇到了无法刷新令牌的间歇性问题。来自服务器的错误
{"error_description":"unknown, invalid, or expired refresh token","error":"invalid_grant"}
刷新令牌不会过期,因为它会持续 24 小时。
我初始化 Tink 的代码类似于:-
private fun manageTink() {
try {
AeadConfig.register()
authenticatedEncryption = generateNewKeysetHandle().getPrimitive(Aead::class.java)
} catch (e: GeneralSecurityException) {
throw RuntimeException(e)
} catch (e: IOException) {
throw RuntimeException(e)
}
}
@Throws(IOException::class, GeneralSecurityException::class)
private fun generateNewKeysetHandle(): KeysetHandle =
AndroidKeysetManager
.Builder()
.withSharedPref(this, TINK_KEYSET_NAME, PREF_FILE_NAME)
.withKeyTemplate(KeyTemplates.get("AES256_GCM"))
.withMasterKeyUri(MASTER_KEY_URI)
.build()
.keysetHandle
这是我的加密/解密代码
import android.util.Base64
import com.google.crypto.tink.Aead
import javax.inject.Inject
const val BASE64_ENCODE_SETTINGS = Base64.NO_WRAP or Base64.NO_PADDING
data class Security @Inject constructor(private val authenticatedEncryption: Aead) {
fun conceal(plainText: String, associatedData: String): String {
val plain64 = Base64.encode(plainText.encodeToByteArray(), BASE64_ENCODE_SETTINGS)
val associated64 = Base64.encode(associatedData.encodeToByteArray(), BASE64_ENCODE_SETTINGS)
val encrypted: ByteArray? = authenticatedEncryption.encrypt(plain64, associated64)
return Base64.encodeToString(encrypted, BASE64_ENCODE_SETTINGS)
}
fun reveal(encrypted64: String, associatedData: String): String {
val encrypted = Base64.decode(encrypted64.encodeToByteArray(), BASE64_ENCODE_SETTINGS)
val associated64 = Base64.encode(associatedData.encodeToByteArray(), BASE64_ENCODE_SETTINGS)
val decrypted: ByteArray? = authenticatedEncryption.decrypt(encrypted, associated64)
return String(Base64.decode(decrypted, BASE64_ENCODE_SETTINGS))
}
}
使用 Base64 编码/解码会是问题吗?我的错误在哪里?