SecureRandom
- Kotlin course
- Advanced
- Lesson 76/83
- 5 min
Learn secure random with SecureRandom.
Cryptographic random with SecureRandom
SecureRandom produces cryptographically strong random values. nextBytes gives bytes; nextInt gives integers. It is slower than java.util.Random but more secure.
Example: val random = SecureRandom(); val bytes = ByteArray(8); random.nextBytes(bytes). bytes fills with 8 random bytes. This pattern is used for key and token generation. setSeed can seed it but carries predictability risk.
Generating bytes with nextBytes
SecureRandom.nextBytes(bytes) fills the given byte array with random values. This is a common way to generate keys and IVs.
Example: val key = ByteArray(16); SecureRandom().nextBytes(key). This produces a 16-byte random AES-128 key. The bytes are unpredictable; each call differs. This pattern is used to produce unique keys for each user.
Practice Print byte size with SecureRandom
In main create val random = SecureRandom(), allocate val bytes = ByteArray(8), call random.nextBytes(bytes) and print println(bytes.size).
Starter code
import java.security.SecureRandom
// in main create a SecureRandom
// fill an 8-byte array, print its sizeSample solution
import java.security.SecureRandom
fun main() {
val random = SecureRandom()
val bytes = ByteArray(8)
random.nextBytes(bytes)
println(bytes.size)
}Expected output
8
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 What distinguishes SecureRandom from java.util.Random?
- It is faster
- It is less random
- It is cryptographically stronger Correct answer
- It only produces Int
Explanation: SecureRandom is cryptographically strong.
2 Match the SecureRandom parts
| Term | Meaning |
|---|---|
SecureRandom() |
Object |
nextBytes(bytes) |
Byte generation |
ByteArray(16) |
Buffer |
cryptographic |
Strength |
3 Complete the nextBytes call
val bytes = ByteArray(8)
SecureRandom().____(bytes)
val bytes = ByteArray(8)
SecureRandom().nextBytes(bytes)
Explanation: nextBytes fills the byte array.