Realm encryption on Android, a few questions


#1

Hello, first of all, thank you for the great product.

I have a few questions on Realm encryption on Android.

  1. Realm uses AES encryption, that works with keys of lengths of 64-128 or 256-bit. Why then encryptionKey() function expects the key to be of 512-bit length?

  2. Android KeyStore on pre-23 devices cannot generate symmetric key for AES. Android versions from 23 and up can generate AES key, but max key size is 256 bit. Given these facts is it OK to generate the key for encryptionKey() using “RSA” KeyPairGenerator, and then load the key as first 512 bits of the corresponding encoded certificate? Please, see below:


private const val keyAlias = "keyMy"
private const val keyStoreType = "AndroidKeyStore"

fun loadKey(): ByteArray? {
    var content = ByteArray(64)
    try {
        val ks = KeyStore.getInstance(keyStoreType)
        ks.load(null)
        content = ks.getCertificate(keyAlias).encoded
    } catch (e: Exception) {
        Logger.e(e)
    }
    return Arrays.copyOfRange(content, 0, 64)
}

fun generateKey(context: Context) {
    val ks = KeyStore.getInstance(keyStoreType)
    ks.load(null)
    try {
        if (!ks.containsAlias(keyAlias)) {
            val start = Calendar.getInstance()
            val end = Calendar.getInstance()
            end.add(Calendar.YEAR, 1)
            val spec = KeyPairGeneratorSpec.Builder(context)
                    .setAlias(keyAlias)
                    .setSubject(X500Principal("CN=Sample Name, O=Android Authority"))
                    .setSerialNumber(BigInteger.ONE)
                    .setStartDate(start.time)
                    .setEndDate(end.time)
                    .build()
            val generator = KeyPairGenerator.getInstance("RSA", keyStoreType)
            generator.initialize(spec)
            generator.generateKeyPair()
        }
    } catch (e: Exception) {
        Logger.e(e)
    }
}

Thank you!