2

I have the following code in Swift:

static func sha256(_ data: Data) -> Data? 
{
   guard let res = NSMutableData(length: Int(CC_SHA256_DIGEST_LENGTH)) else { return nil }
   CC_SHA256((data as NSData).bytes, CC_LONG(data.count), res.mutableBytes.assumingMemoryBound(to: UInt8.self))
   return res as Data
}

I'm unsure how to translate CC_SHA256_DIGEST_LENGTH and CC_SHA256 when doing Android development in Kotlin.

What is the proper way to do this?

Ethan Allen
  • 14,425
  • 24
  • 101
  • 194

2 Answers2

3

A more generic approach (as suggested by user2340612):

private fun hashString(input: String, algorithm: String): String    {
    return MessageDigest.getInstance(algorithm)
        .digest(input.toByteArray())
        .fold("", { str, it -> str + "%02x".format(it) })
} 

List of valid algorithms

Kudos to this guy.

CarHa
  • 1,148
  • 11
  • 31
1

I was able to accomplish what I needed with this:

import android.util.Base64
import com.google.common.hash.Hashing
import java.nio.charset.StandardCharsets

fun calculateSH256(secret: String): String {
   val sha256hex = Hashing.sha256()
       .hashString(secret, StandardCharsets.UTF_8)
       .asBytes()

   return Base64.encodeToString(sha256hex, Base64.DEFAULT)
}

and this in the Gradle file:

dependencies {
    implementation 'com.google.guava:guava:28.0-android'
}
Ethan Allen
  • 14,425
  • 24
  • 101
  • 194
  • Could you add some test cases, too? – kelalaka Aug 21 '19 at 09:08
  • @EthanAllen if you don't want to import a whole new library just for SHA-256 you can have a look at the built-in [MessageDigest](https://developer.android.com/reference/kotlin/java/security/MessageDigest) class. You can get an instance with `MessageDigest.getInstance("SHA-256")` and then call `digest` with your input (if short, otherwise consider chunking the input and feeding the digest via `update`) – user2340612 Aug 21 '19 at 13:12