https://kotlinlang.org logo
#multiplatform
Title
# multiplatform
j

Julius

01/22/2020, 1:55 PM
Hi everyone, Im currently trying to hash a password with SHA-1. But for some reason iOS does emit some zeros Android:
Copy code
val HEX_CHARS = "0123456789abcdef"
        val bytes = MessageDigest.getInstance("SHA-1").digest(stringToHash.toByteArray())
        val result = StringBuilder(bytes.size * 2)

        bytes.forEach {
            val i = it.toInt()
            result.append(HEX_CHARS[i shr 4 and 0x0f])
            result.append(HEX_CHARS[i and 0x0f])
        }

        return result.toString()
iOS:
Copy code
val input = stringToHash.encodeToByteArray()
        val digest = UByteArray(CC_SHA1_DIGEST_LENGTH)
        input.usePinned { inputPinned ->
            digest.usePinned { digestPinned ->
                CC_SHA1(inputPinned.addressOf(0), input.size.convert(), digestPinned.addressOf(0))
            }
        }
        return digest.joinToString(separator = "") { it.toString(16) }
stackoverflow 1
c

Can Orhan

01/22/2020, 4:50 PM
I’ll just leave this here https://sha-mbles.github.io/
o

olonho

01/27/2020, 1:23 PM
for me works as expected:
Copy code
import platform.CoreCrypto.*
import kotlinx.cinterop.*

fun hash(stringToHash: String): String {
  val input = stringToHash.encodeToByteArray()
  val digest = UByteArray(CC_SHA1_DIGEST_LENGTH)
  input.usePinned { inputPinned ->
         digest.usePinned { digestPinned ->
             CC_SHA1(inputPinned.addressOf(0), input.size.convert(), digestPinned.addressOf(0))
          }
  }
 return digest.joinToString(separator = "") { it.toString(16) }
}

fun main() {
   println(hash("123"))
}
prints `40bd0156385fc35165329ea1ff5c5ecbdbbeef`as it should
15 Views