device_fingerprint_service.dart 2.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869
  1. import 'dart:convert';
  2. import 'dart:io';
  3. import 'package:crypto/crypto.dart';
  4. import 'package:device_info_plus/device_info_plus.dart';
  5. import 'package:flutter_secure_storage/flutter_secure_storage.dart';
  6. class DeviceInfo {
  7. final String fingerprint;
  8. final String model;
  9. final String osVersion;
  10. const DeviceInfo({
  11. required this.fingerprint,
  12. required this.model,
  13. required this.osVersion,
  14. });
  15. }
  16. class DeviceFingerprintService {
  17. static const _cacheKey = 'device_fingerprint_v1';
  18. static const _storage = FlutterSecureStorage();
  19. static final DeviceInfoPlugin _deviceInfo = DeviceInfoPlugin();
  20. static Future<DeviceInfo> getDeviceInfo() async {
  21. // 优先读缓存(iOS Keychain 卸载不删除,稳定性更好)
  22. final cached = await _storage.read(key: _cacheKey);
  23. if (cached != null) {
  24. final parts = cached.split('|');
  25. if (parts.length == 3) {
  26. return DeviceInfo(
  27. fingerprint: parts[0],
  28. model: parts[1],
  29. osVersion: parts[2],
  30. );
  31. }
  32. }
  33. String rawId;
  34. String model;
  35. String osVersion;
  36. if (Platform.isAndroid) {
  37. final info = await _deviceInfo.androidInfo;
  38. // ANDROID_ID + manufacturer + model + version
  39. rawId = '${info.id}|${info.manufacturer}|${info.model}|${info.version.release}';
  40. model = '${info.manufacturer} ${info.model}';
  41. osVersion = 'Android ${info.version.release}';
  42. } else if (Platform.isIOS) {
  43. final info = await _deviceInfo.iosInfo;
  44. // identifierForVendor + utsname.machine + systemVersion
  45. rawId = '${info.identifierForVendor}|${info.utsname.machine}|${info.systemVersion}';
  46. model = info.model;
  47. osVersion = 'iOS ${info.systemVersion}';
  48. } else {
  49. rawId = 'unknown';
  50. model = 'unknown';
  51. osVersion = 'unknown';
  52. }
  53. final fingerprint = sha256.convert(utf8.encode(rawId)).toString();
  54. // 写入缓存
  55. await _storage.write(key: _cacheKey, value: '$fingerprint|$model|$osVersion');
  56. return DeviceInfo(fingerprint: fingerprint, model: model, osVersion: osVersion);
  57. }
  58. }