Skip to content

Instantly share code, notes, and snippets.

@Jaypatelbond
Created December 4, 2025 07:55
Show Gist options
  • Select an option

  • Save Jaypatelbond/5d43dd1b2111af137428b32e1767b050 to your computer and use it in GitHub Desktop.

Select an option

Save Jaypatelbond/5d43dd1b2111af137428b32e1767b050 to your computer and use it in GitHub Desktop.
@Singleton
class UserPreferencesSerializer @Inject constructor(
private val cryptoManager: CryptoManager
) : Serializer<UserPreferences> {
override val defaultValue: UserPreferences = UserPreferences.getDefaultInstance()
override suspend fun readFrom(input: InputStream): UserPreferences {
return try {
// Decrypt the stream before parsing
val decryptedStream = cryptoManager.decrypt(input)
UserPreferences.parseFrom(decryptedStream)
} catch (exception: InvalidProtocolBufferException) {
throw CorruptionException("Cannot read proto.", exception)
}
}
override suspend fun writeTo(t: UserPreferences, output: OutputStream) {
// Encrypt the stream while writing
val encryptedStream = cryptoManager.encrypt(output)
t.writeTo(encryptedStream)
encryptedStream.close() // Important: close to finalize encryption blocks
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment