57 lines
2.1 KiB
Dart
57 lines
2.1 KiB
Dart
import 'dart:convert';
|
|
|
|
import 'package:crypto/crypto.dart';
|
|
|
|
/// Pure port of the backend's `DeviceController.GetDeviceCode`:
|
|
///
|
|
/// ```csharp
|
|
/// var currentDate = DateTime.Now.ToString("yyyyMMdd");
|
|
/// var rawData = request.MacAddress + currentDate + secret;
|
|
/// var hash = SHA256.HashData(Encoding.UTF8.GetBytes(rawData));
|
|
/// var value = uint.Parse(Convert.ToHexString(hash, 0, 4), NumberStyles.HexNumber);
|
|
/// var password = (value % 100000000L).ToString("D8");
|
|
/// ```
|
|
///
|
|
/// [mac] is hashed exactly as given (no normalization), [date] must already be
|
|
/// formatted as `yyyyMMdd`.
|
|
String generateDeviceCode({
|
|
required String mac,
|
|
required String date,
|
|
required String secret,
|
|
}) {
|
|
final bytes = sha256.convert(utf8.encode(mac + date + secret)).bytes;
|
|
// First 4 bytes as a big-endian uint32. Multiplication instead of shifts so
|
|
// the result is also correct on platforms with 32-bit bitwise ops (web).
|
|
final value =
|
|
bytes[0] * 16777216 + bytes[1] * 65536 + bytes[2] * 256 + bytes[3];
|
|
return (value % 100000000).toString().padLeft(8, '0');
|
|
}
|
|
|
|
/// Formats a date as `yyyyMMdd` (the backend's format, invariant culture).
|
|
String formatDateForCode(DateTime date) {
|
|
final y = date.year.toString().padLeft(4, '0');
|
|
final m = date.month.toString().padLeft(2, '0');
|
|
final d = date.day.toString().padLeft(2, '0');
|
|
return '$y$m$d';
|
|
}
|
|
|
|
/// Mirrors the web page: keep only hex digits, cap at 12, lowercase, and join
|
|
/// pairs with ':' (e.g. `742584C0024A` -> `74:25:84:c0:02:4a`).
|
|
///
|
|
/// Partial input is formatted progressively (`7425` -> `74:25`, `742` -> `74:2`).
|
|
String formatMac(String input) {
|
|
final hex = input.toLowerCase().replaceAll(RegExp(r'[^0-9a-f]'), '');
|
|
final digits = hex.length > 12 ? hex.substring(0, 12) : hex;
|
|
final pairs = <String>[];
|
|
for (var i = 0; i < digits.length; i += 2) {
|
|
pairs.add(
|
|
digits.substring(i, i + 2 > digits.length ? digits.length : i + 2),
|
|
);
|
|
}
|
|
return pairs.join(':');
|
|
}
|
|
|
|
/// True when [formattedMac] contains a complete 12-hex-digit MAC.
|
|
bool isCompleteMac(String formattedMac) =>
|
|
RegExp(r'^([0-9a-f]{2}:){5}[0-9a-f]{2}$').hasMatch(formattedMac);
|