Hashing
- Kotlin course
- Advanced
- Lesson 73/83
- 5 min
Learn hashing with java.security.MessageDigest.
Hashing with MessageDigest
MessageDigest digests an input to a fixed length. SHA-256 is a common algorithm; it produces a 32-byte digest. The same input always yields the same digest.
Example: val md = MessageDigest.getInstance("SHA-256"); val bytes = md.digest("abc".toByteArray()). bytes.size returns 32. digest hashes the input; the same input gives a deterministic result. Hashing is used for password storage and data integrity.
toByteArray and digest
For hashing the input is first converted to a byte array with toByteArray(). digest both adds the input and returns the digest. You can append in pieces with update.
Example: md.update("part1".toByteArray()); md.update("part2".toByteArray()); val bytes = md.digest(). This gives the digest of "part1part2". This pattern is used to hash large files in chunks.
Practice Print SHA-256 hash byte size
In main take val md = MessageDigest.getInstance("SHA-256"), hash with val bytes = md.digest("abc".toByteArray()) and print println(bytes.size).
Starter code
import java.security.MessageDigest
// in main hash abc with SHA-256
// print the byte sizeSample solution
import java.security.MessageDigest
fun main() {
val md = MessageDigest.getInstance("SHA-256")
val bytes = md.digest("abc".toByteArray())
println(bytes.size)
}Expected output
32
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 How many bytes does MessageDigest.getInstance("SHA-256") produce?
- 128
- 16
- 64
- 32 Correct answer
Explanation: SHA-256 produces a 32-byte (256-bit) digest.
2 Complete the MessageDigest getInstance call
val md = MessageDigest.____("SHA-256")
val md = MessageDigest.getInstance("SHA-256")
Explanation: getInstance selects the algorithm.
3 Match the hash parts
| Term | Meaning |
|---|---|
MessageDigest |
Hash object |
getInstance("SHA-256") |
Algorithm selection |
digest("abc".toByteArray()) |
Hashing |
32 |
Byte size |