generateSerialNumberBigInt static method
Generates a cryptographically strong random serial number.
bytes should be between 8 and 20 for production use (RFC 5280).
Implementation
static BigInt generateSerialNumberBigInt({int bytes = 16}) {
if (bytes < 4 || bytes > 20) {
throw RangeError.range(bytes, 4, 20, 'bytes');
}
final Uint8List serialBytes = _secureRandom.nextBytes(bytes);
// Ensure positive and non-zero by clearing MSB and setting LSB.
serialBytes[0] = serialBytes[0] & 0x7F;
serialBytes[serialBytes.length - 1] |= 0x01;
BigInt serial = BigInt.zero;
for (final int b in serialBytes) {
serial = (serial << 8) | BigInt.from(b);
}
return serial == BigInt.zero ? BigInt.one : serial;
}