Hi! I'm currently integrating Moshi with androidx'...
# squarelibraries
c
Hi! I'm currently integrating Moshi with androidx's new DataStore. Everything was going swimmingly until I tried to make use of Okio's
CipherSource
and
CipherSink
to encrypt the JSON on disk. From what I can tell, it's probably me misusing Okio. I'm attempting to save the Cipher's initialisation vector into a
Sink
before then converting that into a
CipherSink
. This ends up looking like:
Copy code
fun getEncryptedSink(output: OutputStream): Sink {
  val cipher = getEncryptionCipher()

  return output.sink().buffer().use {
    it.writeInt(cipher.iv.size)
    it.write(cipher.iv)
    it.buffer.cipherSink(cipher)
  }
}
The reason I want to write the IV to disk is so I can use it to construct a decryption cipher on the way back out:
Copy code
fun getDecryptedSource(input: InputStream): Source {
  return input.source().buffer().use {
    val ivSize = it.readInt().toLong()
    val iv = it.readByteArray(ivSize)
    val cipher = getDecryptionCipher(iv)
    it.cipherSource(cipher)
  }
}
But this approach makes DataStore extremely unhappy, crashing when it attempts to write the data to disk. Specifically, a call to
Copy code
stream.fd.sync()
fails. Anyone know what's wrong with my approach?