I want to do AES-256-GCM encryption on Android API 15+. Here is my code:
import android.util.Base64
import java.security.SecureRandom
import javax.crypto.Cipher
import javax.crypto.SecretKey
import javax.crypto.spec.SecretKeySpec
import javax.crypto.spec.IvParameterSpec
fun encryptGCM(key: String, plaintext: String): String {
val decodedKey = Base64.decode(key, 0)
val secretKey: SecretKey = SecretKeySpec(decodedKey, 0, decodedKey.size, "AES")
val secureRandom = SecureRandom()
val iv = ByteArray(12)
secureRandom.nextBytes(iv)
val cipher = Cipher.getInstance("AES/GCM/NoPadding")
cipher.init(Cipher.ENCRYPT_MODE, secretKey, IvParameterSpec(iv))
val cipherText: ByteArray = cipher.doFinal(plaintext.toByteArray())
return Base64.encodeToString(iv + cipherText, 0)
}
I have two questions:
Since I'm targeting pre v4.4, do I need to worry about the
SecureRandom
vulnerability in this blog post, given my use case? https://android-developers.googleblog.com/2013/08/some-securerandom-thoughts.htmlIs using
IvParameterSpec
instead ofGCMParameterSpec
fine? I'm using theIv
version becauseGcmParameterSpec
is only available in API level 19+. As far as I understand, the only difference is the GCM version allows me to specify a tag length, but the default tag length in my code will be 128, which seems fine.
Thanks for any insight!