Kotlin SHA-256 and PBKDF2 on the JVM
Kotlin on the JVM can use the Java security libraries directly. MessageDigest computes hashes such as SHA-256. A hash is deterministic and one-way, and a tiny change in the input produces a completely different digest. Hashes are used to check integrity. Convert text to bytes with an explicit charset before hashing, so that the result does not depend on the platform.
Kotlin
import java.security.MessageDigest
import java.security.SecureRandom
import javax.crypto.SecretKeyFactory
import javax.crypto.spec.PBEKeySpec
fun hex(bytes: ByteArray): String = bytes.joinToString("") { "%02x".format(it) }
fun derive(password: String, salt: ByteArray): ByteArray {
val spec = PBEKeySpec(password.toCharArray(), salt, 600_000, 256)
return SecretKeyFactory.getInstance("PBKDF2WithHmacSHA256").generateSecret(spec).encoded
}
fun main() {
val sha = MessageDigest.getInstance("SHA-256")
println(hex(sha.digest("abc".toByteArray(Charsets.UTF_8))))
println(hex(sha.digest("abd".toByteArray(Charsets.UTF_8))))
val salt = ByteArray(16).also { SecureRandom().nextBytes(it) }
val stored = derive("correct horse", salt)
println("hash length: ${stored.size} bytes")
println("right password: ${MessageDigest.isEqual(stored, derive("correct horse", salt))}")
println("wrong password: ${MessageDigest.isEqual(stored, derive("wrong guess", salt))}")
}