3

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:

  1. 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.html

  2. Is using IvParameterSpec instead of GCMParameterSpec fine? I'm using the Iv version because GcmParameterSpec 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!

Dan
  • 641
  • 9
  • 25

0 Answers0