Files
kooltab/lib/services/pin_lock_service.dart
T
2026-07-27 21:32:03 +02:00

54 lines
1.4 KiB
Dart

import 'dart:convert';
import 'dart:math';
import 'package:crypto/crypto.dart';
import 'package:flutter_secure_storage/flutter_secure_storage.dart';
class PinLockService {
PinLockService({FlutterSecureStorage? storage})
: _storage = storage ?? const FlutterSecureStorage();
static const _saltKey = 'pin_salt';
static const _hashKey = 'pin_hash';
final FlutterSecureStorage _storage;
Future<bool> hasPin() async {
final hash = await _storage.read(key: _hashKey);
return hash != null && hash.isNotEmpty;
}
Future<void> setPin(String pin) async {
final salt = _generateSalt();
final hash = _hash(pin, salt);
await _storage.write(key: _saltKey, value: salt);
await _storage.write(key: _hashKey, value: hash);
}
Future<bool> verifyPin(String pin) async {
final salt = await _storage.read(key: _saltKey);
final storedHash = await _storage.read(key: _hashKey);
if (salt == null || storedHash == null) return false;
return _hash(pin, salt) == storedHash;
}
Future<void> clearPin() async {
await _storage.delete(key: _saltKey);
await _storage.delete(key: _hashKey);
}
String _generateSalt([int length = 16]) {
final random = Random.secure();
final bytes = List<int>.generate(length, (_) => random.nextInt(256));
return base64UrlEncode(bytes);
}
String _hash(String pin, String salt) {
final bytes = utf8.encode('$salt:$pin');
return sha256.convert(bytes).toString();
}
}