Compute SHA256 Hash in Android/Java and C#

前端 未结 2 1926
孤独总比滥情好
孤独总比滥情好 2020-12-14 01:04

I am trying to generate a SHA256 hash in android, that I then pass to an ASP.NET Web API web service and compare the hash there. As such, I need to construct a hash in Andro

相关标签:
2条回答
  • 2020-12-14 01:22

    Your Java code is wrong: you are adding the input bytes twice. If you are calculating this in one go, you need to either call only digest(bytes) or call digest() after update(bytes);

    0 讨论(0)
  • 2020-12-14 01:40

    I was looking for a Kotlin version for my Android app.

    I could not find one; here is what I came up with:

    fun String.getSha256(): String {
        val digest = MessageDigest.getInstance("SHA-256").apply { reset() }
        val byteData: ByteArray = digest.digest(this.toByteArray())
        return StringBuffer().apply {
            byteData.forEach {
                append(((it.toInt() and 0xff) + 0x100).toString(16).substring(1))
            }
        }.toString()
    }
    
    0 讨论(0)
提交回复
热议问题