Summary - Security
- Kotlin course
- Advanced
- Lesson 78/83
- 5 min
Combine hash, HMAC and AES to write an encryptor.
Summary - Security
In this group you saw the security tools: hash with MessageDigest, HMAC with Mac, AES with Cipher, cryptographic random with SecureRandom and PBKDF2 with SecretKeyFactory.
This lesson includes a small task that combines three of them: you will hash a text with SHA-256, convert it to hex and print its length. This pattern brings together the foundation of security tools.
Practice Summary: SHA-256 hex length
In main take val md = MessageDigest.getInstance("SHA-256"), hash with val bytes = md.digest("hello".toByteArray()). Convert to hex with val hex = bytes.joinToString("") { "%02x".format(it) } and print println(hex.length).
Starter code
import java.security.MessageDigest
// in main hash hello with SHA-256
// convert to hex, print hex lengthSample solution
import java.security.MessageDigest
fun main() {
val md = MessageDigest.getInstance("SHA-256")
val bytes = md.digest("hello".toByteArray())
val hex = bytes.joinToString("") { "%02x".format(it) }
println(hex.length)
}Expected output
64
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 Which tool verifies integrity one-way?
- MessageDigest Correct answer
- Cipher
- SecureRandom
- Mac
Explanation: MessageDigest produces one-way hash.
2 Match the security tools
| Term | Meaning |
|---|---|
MessageDigest |
Hash |
Mac |
HMAC |
Cipher |
AES encryption |
SecretKeyFactory |
PBKDF2 |
3 Complete the joinToString hex length
val hex = bytes.joinToString("") { "%02x".format(it) }
println(hex.____)
val hex = bytes.joinToString("") { "%02x".format(it) }
println(hex.length)
Explanation: String.length gives the hex length.