Added js _util functions

This commit is contained in:
Ugljesa Jovanovic committed 2020-09-26 23:58:45 +02:00
1 parent f113f7805d
commit 4af1477c90
5 files changed
+161 -69

No files matched your search

@@ -194,9 +194,20 @@ interface JsSodiumInterface {
// ---- Password hashing end ----
// ---- Utils ----
//util
fun memzero(array: Uint8Array)
fun memcmp(first: Uint8Array, second: Uint8Array) : Boolean
fun memzero(data: Uint8Array)
fun pad(data : Uint8Array, blocksize: Int) : Uint8Array
fun unpad(data: Uint8Array, blocksize: Int) : Uint8Array
fun to_base64(data: Uint8Array, variant: Int) : String
fun to_hex(data: Uint8Array) : String
fun to_string(data: Uint8Array) : String
fun from_base64(data: String, variant: Int): Uint8Array
fun from_hex(data : String): Uint8Array
fun from_string(data : String): Uint8Array
// ---- Utils end ----
@@ -0,0 +1,50 @@
package com.ionspin.kotlin.crypto.util
import com.ionspin.kotlin.crypto.getSodium
import ext.libsodium.com.ionspin.kotlin.crypto.toUByteArray
import ext.libsodium.com.ionspin.kotlin.crypto.toUInt8Array
actual object LibsodiumUtil {
actual fun memcmp(first: UByteArray, second: UByteArray): Boolean {
return getSodium().memcmp(first.toUInt8Array(), second.toUInt8Array())
}
actual fun memzero(target: UByteArray) {
// libsodium.js does this as well, and theres no clear way at the moment of casting ubytearray to uint8array
//although I feel like there should be a way to work around it
target.forEachIndexed {
index, _ -> target[index] = 0U
}
}
actual fun pad(unpaddedData: UByteArray, blocksize: Int): UByteArray {
return getSodium().pad(unpaddedData.toUInt8Array(), blocksize).toUByteArray()
}
actual fun unpad(paddedData: UByteArray, blocksize: Int): UByteArray {
return getSodium().unpad(paddedData.toUInt8Array(), blocksize).toUByteArray()
}
actual fun toBase64(
data: UByteArray,
variant: Base64Variants
): String {
return getSodium().to_base64(data.toUInt8Array(), variant.value)
}
actual fun toHex(data: UByteArray): String {
return getSodium().to_hex(data.toUInt8Array())
}
actual fun fromBase64(
data: String,
variant: Base64Variants
): UByteArray {
return getSodium().from_base64(data, variant.value).toUByteArray()
}
actual fun fromHex(data: String): UByteArray {
return getSodium().from_hex(data).toUByteArray()
}
}