HMAC
- Kotlin course
- Advanced
- Lesson 74/83
- 5 min
Learn message authentication with HMAC.
Signed hash with HMAC
HMAC is a hash signed with a secret key. The Mac class uses the HmacSHA256 algorithm. The receiver verifies the signature with the same key.
Example: val mac = Mac.getInstance("HmacSHA256"); mac.init(SecretKeySpec("key".toByteArray(), "HmacSHA256")); val result = mac.doFinal("data".toByteArray()). result.size returns 32. HMAC provides both integrity and authenticity; it cannot be verified without the key.
Keys with SecretKeySpec
SecretKeySpec turns a byte array into a key. It is passed to Mac.init; signing uses this key.
Example: val key = SecretKeySpec("secret".toByteArray(), "HmacSHA256"); mac.init(key). The key is kept secret; shared with the receiver. Without the right key the signature cannot be verified. This pattern is used for API request signing and webhook verification.
Practice Print HMAC signature byte size
In main take val mac = Mac.getInstance("HmacSHA256"), call mac.init(SecretKeySpec("key".toByteArray(), "HmacSHA256")), sign with val result = mac.doFinal("data".toByteArray()) and print println(result.size).
Starter code
import javax.crypto.Mac
import javax.crypto.spec.SecretKeySpec
// in main take HmacSHA256, init with key
// sign data, print byte sizeSample solution
import javax.crypto.Mac
import javax.crypto.spec.SecretKeySpec
fun main() {
val mac = Mac.getInstance("HmacSHA256")
mac.init(SecretKeySpec("key".toByteArray(), "HmacSHA256"))
val result = mac.doFinal("data".toByteArray())
println(result.size)
}Expected output
32
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 Complete the Mac getInstance call
val mac = Mac.____("HmacSHA256")
val mac = Mac.getInstance("HmacSHA256")
Explanation: Mac.getInstance selects the algorithm.
2 What is the main purpose of HMAC?
- Integrity and authenticity Correct answer
- Encryption
- Compression
- Random generation
Explanation: HMAC provides both integrity and authenticity.
3 Match the HMAC parts
| Term | Meaning |
|---|---|
Mac.getInstance |
Mac object |
SecretKeySpec |
Key |
mac.init |
Key loading |
mac.doFinal |
Signature generation |