Adding pwhash native and tests

This commit is contained in:
Ugljesa Jovanovic committed 2020-09-21 19:07:06 +02:00
1 parent 65bf54765f
commit 2b4d8aa4b1
4 files changed
+110 -29

No files matched your search

@@ -4,9 +4,11 @@ import com.ionspin.kotlin.crypto.util.toPtr
import kotlinx.cinterop.addressOf
import kotlinx.cinterop.convert
import kotlinx.cinterop.pin
import kotlinx.cinterop.toCValues
import libsodium.crypto_pwhash
import libsodium.crypto_pwhash_str
import libsodium.crypto_pwhash_str_needs_rehash
import libsodium.crypto_pwhash_str_verify
actual object PasswordHash {
/**
@@ -30,7 +32,7 @@ actual object PasswordHash {
val hashedPasswordPinned = hashedPassword.pin()
val saltPinned = salt.pin()
crypto_pwhash(
val hashingResult = crypto_pwhash(
hashedPasswordPinned.toPtr(),
outputLength.convert(),
password,
@@ -42,6 +44,9 @@ actual object PasswordHash {
)
saltPinned.unpin()
hashedPasswordPinned.unpin()
if (hashingResult != 0) {
throw PasswordHashingFailed()
}
return hashedPassword
}
@@ -56,8 +61,8 @@ actual object PasswordHash {
* and other data stores. No extra information has to be stored in order to verify the password.
* The function returns 0 on success and -1 if it didn't complete successfully.
*/
actual fun str(password: String, opslimit: ULong, memlimit: Int): String {
val output = ByteArray(crypto_pwhash_STRBYTES.toInt())
actual fun str(password: String, opslimit: ULong, memlimit: Int): UByteArray {
val output = ByteArray(crypto_pwhash_STRBYTES)
val outputPinned = output.pin()
crypto_pwhash_str(
outputPinned.addressOf(0),
@@ -68,7 +73,7 @@ actual object PasswordHash {
)
outputPinned.unpin()
return output.decodeToString()
return output.asUByteArray()
}
/**
@@ -78,20 +83,32 @@ actual object PasswordHash {
* It returns -1 on error. If it happens, applications may want to compute a correct hash the next time the user logs in.
*/
actual fun strNeedsRehash(
password: String,
passwordHash: UByteArray,
opslimit: ULong,
memlimit: Int
): Boolean {
val password = password.encodeToByteArray()
crypto_pwhash_str_needs_rehash(
,
): Int {
val result = crypto_pwhash_str_needs_rehash(
passwordHash.asByteArray().toCValues(),
opslimit,
memlimit.convert()
)
return result
}
actual fun strVerify(passwordHash: String, password: UByteArray): Boolean {
TODO("Not yet implemented")
/**
* his function verifies that str is a valid password verification string (as generated by crypto_pwhash_str()) for passwd whose length is passwdlen.
* str has to be zero-terminated.
* It returns 0 if the verification succeeds, and -1 on error.
*/
actual fun strVerify(passwordHash: UByteArray, password: String): Boolean {
val result = crypto_pwhash_str_verify(
passwordHash.asByteArray().toCValues(),
password,
password.length.convert()
)
return result == 0
}
}
}