Sketching further API

This commit is contained in:
Ugljesa Jovanovic 2020-06-21 22:06:09 +02:00 committed by Ugljesa Jovanovic
parent 2f0f174b33
commit f107db3312
No known key found for this signature in database
GPG Key ID: 178E6DFCECCB0E0F
2 changed files with 22 additions and 10 deletions

View File

@ -70,21 +70,29 @@ object Primitives : CryptoProvider {
} }
inline class EncryptableString(val content: String) : Encryptable { inline class EncryptableString(val content: String) : Encryptable<EncryptableString> {
override fun encryptableData(): UByteArray { override fun toEncryptableForm(): UByteArray {
return content.encodeToUByteArray() return content.encodeToUByteArray()
} }
override fun fromEncryptableForm(): (UByteArray) -> EncryptableString {
return { uByteArray ->
EncryptableString(uByteArray.toByteArray().decodeToString())
}
}
fun asString() : String = content fun asString() : String = content
} }
fun String.asEncryptableString() : EncryptableString { fun String.asEncryptableString() : EncryptableString {
return EncryptableString(this) return EncryptableString(this)
} }
interface Encryptable { interface Encryptable<T> {
fun encryptableData() : UByteArray fun toEncryptableForm() : UByteArray
fun fromEncryptableForm() : (UByteArray) -> T
} }
data class HashedData(val hash: UByteArray) { data class HashedData(val hash: UByteArray) {
@ -101,7 +109,9 @@ data class SymmetricKey(val value : UByteArray) {
} }
} }
data class EncryptedData(val encrypted: UByteArray) data class EncryptedData internal constructor(val ciphertext: UByteArray, val nonce: UByteArray) {
}
object PublicApi { object PublicApi {
@ -115,16 +125,18 @@ object PublicApi {
} }
} }
object Symmetric { object Symmetric {
fun encrypt(key: SymmetricKey, data : Encryptable, additionalData : UByteArray = ubyteArrayOf()) : EncryptedData { fun encrypt(key: SymmetricKey, data : Encryptable<*>, additionalData : UByteArray = ubyteArrayOf()) : EncryptedData {
if (key.value.size != 32) { if (key.value.size != 32) {
throw RuntimeException("Invalid key size! Required 32, supplied ${key.value.size}") throw RuntimeException("Invalid key size! Required 32, supplied ${key.value.size}")
} }
val nonce = SRNG.getRandomBytes(24) val nonce = SRNG.getRandomBytes(24)
return EncryptedData(XChaCha20Poly1305Pure.encrypt(key.value, nonce, data.encryptableData(), additionalData) + nonce) return EncryptedData(XChaCha20Poly1305Pure.encrypt(key.value, nonce, data.toEncryptableForm(), additionalData), nonce)
} }
fun <T: Encryptable> decrypt(encryptedData : EncryptedData) : T { fun <T: Encryptable<T>> decrypt(key: SymmetricKey, encryptedData : EncryptedData, additionalData: UByteArray, byteArrayDeserializer : (UByteArray) -> T) : T {
TODO() return byteArrayDeserializer(XChaCha20Poly1305Pure.decrypt(key.value, encryptedData.nonce, encryptedData.ciphertext, additionalData))
} }
} }
} }