getUniqueIdentifier method

  1. @override
Future<String?> getUniqueIdentifier()
override

Returns the unique device identifier for the current platform.

May return null if the platform cannot provide a valid identifier.

Platform behavior:

  • Android: Returns Settings.Secure.ANDROID_ID
  • iOS: Returns UIDevice.identifierForVendor
  • macOS: Returns IOPlatformUUID using IOKit (macOS 12+: kIOMainPortDefault, older: kIOMasterPortDefault)
  • Windows: Reads the registry value HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Cryptography\MachineGuid
  • Linux: Reads from /etc/machine-id
  • Web: Returns a fingerprint-based hash if possible; otherwise, a random UUID is generated and stored in localStorage

Implementation

@override
Future<String?> getUniqueIdentifier() async {
  try {
    final info = [
      navigator.userAgent,
      navigator.languages.toDart.cast<String>().join(','),
      navigator.platform,
      navigator.hardwareConcurrency.toString(),
      navigator.maxTouchPoints.toString(),
      DateTime.now().timeZoneName,
    ].join('|');

    final data = Uint8List.fromList(utf8.encode(info));
    final digestBuffer = await window.crypto.subtle
        .digest('SHA-256', data.jsify() as JSObject)
        .toDart;

    return bufferToHex(digestBuffer as JSArrayBuffer);
  } catch (_) {
    const key = 'unique_device_id_fallback';
    var stored = window.localStorage.getItem(key);
    if (stored == null) {
      stored = generateUUID();
      window.localStorage.setItem(key, stored);
    }
    return stored;
  }
}