I am a investigating the decorator pattern in kotlin and would like to encrypt/decrypt data class fields with a cryptography decorator.
One thing I do not understand is that the decorator approach requires an instance of the class being decorated. which means the data class fields I wish to encrypt will already containing plaintext before the decorator has an opportunity to encrypt any values.
I cannot find any examples of how to implement encryption/decryption using the decorator pattern related to class constructor fields. is it possible to achieve my desired implementation.
I am attempting to create this cryptography decorator to allow me to persist plaintext data as encrypted strings in my current android application room local database.
I have achieved the desired result using a room type converter for my custom data type field as shown below, however I would also like an alternative approach of employing a decorator class combined with kotlin delegation.
class EncryptedStringConverter : KoinComponent {
private val cryptographer: Cryptographer by inject()
@TypeConverter
fun fromEncryptedStringToString(encryptedString: EncryptedString): String = encrypt(encryptedString.plaintText)
@TypeConverter
fun fromPlaintextToEncryptedString(plaintext: String): EncryptedString = decrypt(plaintext)
private fun encrypt(plaintext: String): String = cryptographer.conceal(plainText = plaintext)
private fun decrypt(encryptedString: String): EncryptedString = EncryptedString(cryptographer.reveal(encryptedString))
}
data class EncryptedString(val plaintText: String)
@Entity(
tableName = "user_table"
)
data class UserDO(
var firstName: EncryptedString,
var lastName: EncryptedString,
var email: EncryptedString,
var companyName: EncryptedString,
)