Search code examples
androidkotlinaesencryption-symmetric

Working with ByteArrays and SecretKeySpec in Kotlin


I have a seemingly simple task..

Take a file, open it, take the byte stream as a AES key, and instantiate a javax.crypto.spec.SecretKeySpec within Android Kotlin

if (key == null) {

  val my_bytes: ByteArray = byteArrayOf(0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0) 
  val algo = "AES"

  val secretKey = SecretKeySpec(my_bytes, algo)

  saveSecretKey(sharedPref, secretKey!!)
  return secretKey
}

Edit: SecretKeySpec() works now. I just need to know how to put the bytes from the file into the android app properly. Is hard coding in the app insecure? Should I store the key as a file and read it in from the android file system?


Solution

  • If you store the key as a file on the external drive the following things will happen:

    1. You will need permission from the user to read/write to the external drive
    2. Because the key is on the external drive it is susceptible to: 2.1 Being deleted by the user 2.2 Being read by an app/person other than the one you intended it for

    Since secret key is symmetric, and can be used for both encryption and decryption.

    Now, for our birds:

    To load the file from the disk: This explains it quite well