20 lines
675 B
Dart
20 lines
675 B
Dart
import 'dart:math';
|
|
|
|
/// Random hex id from a cryptographic RNG, e.g. for per-install identifiers.
|
|
String randomHexId({int bytes = 16}) {
|
|
final random = Random.secure();
|
|
return List<int>.generate(
|
|
bytes,
|
|
(_) => random.nextInt(256),
|
|
).map((b) => b.toRadixString(16).padLeft(2, '0')).join();
|
|
}
|
|
|
|
/// Random RFC 4122 version-4 UUID, for ids a server expects in UUID form.
|
|
String randomUuidV4() {
|
|
final hex = randomHexId();
|
|
final variant = (int.parse(hex[16], radix: 16) & 0x3 | 0x8).toRadixString(16);
|
|
return '${hex.substring(0, 8)}-${hex.substring(8, 12)}-'
|
|
'4${hex.substring(13, 16)}-$variant${hex.substring(17, 20)}-'
|
|
'${hex.substring(20)}';
|
|
}
|