1

I have a table with messages in a chat app and i want to use TripleDes encryption in the column body of the table in my Room Database. What i do now is that whenever i has an array of new messages i loop through them and change the .body field to TripleDes.encrypt(body)

// TripleDes encryption to inserted messages
   messageDtoList.forEach {
      if (it.body.isNotEmpty())
         it.body = TripleDesEncrypt.encrypt(it.body, Params.TRIPLE_DES_KEY)
     }               
   AppDatabase.invoke(MyApplication.instance).messageDao().insert(messageDtoList)

I wanted to know if there is a better and more formal way to do this

james04
  • 1,580
  • 2
  • 20
  • 46

1 Answers1

6

Using TypeConverter could be useful. I wrote a class named DecryptedString which wraps String and inner Converter class which handles encryption/decryption processes.

class DecryptedString(var value: String = "") {

    class Converter {
        @TypeConverter
        fun decrypt(encrypted: String): DecryptedString {
            return DecryptedString(TripleDesEncrypt.decrypt(encrypted, Params.TRIPLE_DES_KEY))
        }

        @TypeConverter
        fun encrypt(decrypted: DecryptedString): String {
            return TripleDesEncrypt.encrypt(decrypted.value, Params.TRIPLE_DES_KEY)
        }
    }
}

Then instead of using String type for body field, you have to use DecryptedString type in your MessageModel class.


@Entity
data class MessageModel(
        @PrimaryKey
        var uid: Int,

        @TypeConverters(DecryptedString.Converter::class)
        @ColumnInfo(name = "decrypted_body")
        var body: DecryptedString

        //Other fields
)
Mir Milad Hosseiny
  • 2,769
  • 15
  • 19
  • Hmm....yeah seems ok! So when i insert a proper string it will get automatically encrypted? And when i select a query it will get automatically decrypted also? Or the decryption i have to do it manually? – james04 Jan 15 '20 at 12:31
  • 1
    @james04: You don't need to do anything manually. All encryption/decryption processes are performed automatically. – Mir Milad Hosseiny Jan 15 '20 at 13:13
  • Hello. Its been a while but i want to inform you that the solution you proposed finally didnt work. TypeConverters take a specific type (String) and convert it to another Type (lets say Date). Does now work in the same Type. Perhaps you have another idea? – james04 Apr 09 '20 at 20:37
  • @james04 As you mentioned it doesn't work for the same types, so this the reason that I defined `DecryptedString` class. – Mir Milad Hosseiny Apr 10 '20 at 07:40
  • @james04 did you try search on this encrypted data? – Balwinder SIngh May 18 '20 at 12:40
  • @MirMiladHosseiny Where i can find TripleDesEncrypt – Sunil Sep 01 '20 at 13:11
  • @Sunil It's a custom class with two static methods for encryption and decryption. You can replace it with your desired cryptography algorithm. – Mir Milad Hosseiny Sep 03 '20 at 11:02