Files
kooltab/lib/services/pin_lock_service.dart
2026-08-07 03:09:59 +02:00

61 lines
1.6 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,
String saltKey = _defaultSaltKey,
String hashKey = _defaultHashKey,
}) : _storage = storage ?? const FlutterSecureStorage(),
_saltKey = saltKey,
_hashKey = hashKey;
static const _defaultSaltKey = 'pin_salt';
static const _defaultHashKey = 'pin_hash';
final FlutterSecureStorage _storage;
final String _saltKey;
final String _hashKey;
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();
}
}