Secure random
- Dart course
- Advanced
- Lesson 70/83
- 5 min
Learn secure random with Random.secure.
Random.secure
Random.secure is Dart's cryptographically secure random number generator. It lives in the dart:math library. Unlike the regular Random it is unpredictable; it is used for passwords, tokens and session IDs.
Example: import 'dart:math'; final r = Random.secure(); final token = List<int>.generate(32, (_) => r.nextInt(256));. This produces a 32-byte random token. Each byte takes a random value from 0 to 255. You can base64-encode this token and use it as a bearer token. Random() is predictable; it is not suitable for security.
Token generation
To produce a secure token you use Random.secure. The typical pattern is List<int>.generate(length, (_) => r.nextInt(256)). This produces a list where each byte is a random value from 0 to 255. You base64-encode the list to get a string token.
Example: a 32-byte token becomes a 44-character base64 string. This can be used as a session ID, API key or reset token. The key point is to always use Random.secure() instead of Random(); otherwise the token is predictable and security is compromised.
Practice A token generation function
Add import 'dart:math';. Define generateToken with final r = Random.secure(); and return List<int>.generate(32, (_) => r.nextInt(256)); inside. In main add print('Random.secure: cryptographic random') and print('Token size: 32 bytes').
Starter code
// import the dart:math library
// define generateToken (32-byte token with Random.secure)
void main() {
// print secure random info
}Sample solution
import 'dart:math';
List<int> generateToken() {
final r = Random.secure();
return List<int>.generate(32, (_) => r.nextInt(256));
}
void main() {
print('Random.secure: cryptographic random');
print('Token size: 32 bytes');
}Expected output
Random.secure: cryptographic random Token size: 32 bytes
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 What does Random.secure provide?
- Predictable numbers
- Cryptographically secure random Correct answer
- Fixed numbers
- Same number
Explanation: Random.secure provides cryptographically secure random.
2 Match the Random.secure parts
| Term | Meaning |
|---|---|
Random.secure |
Secure random |
dart:math |
Library |
nextInt |
Integer |
nextDouble |
Decimal |
3 The Random.secure call
final r = ____();
final r = Random.secure();
Explanation: Random.secure() creates a secure random generator.