37 lines
996 B
Dart
37 lines
996 B
Dart
|
|
import 'dart:convert';
|
||
|
|
import 'dart:math';
|
||
|
|
import 'dart:typed_data';
|
||
|
|
import 'package:crypto/crypto.dart';
|
||
|
|
|
||
|
|
class HashUtils {
|
||
|
|
static final _random = Random.secure();
|
||
|
|
|
||
|
|
static String generateHash() {
|
||
|
|
final bytes = List<int>.generate(32, (_) => _random.nextInt(256));
|
||
|
|
return sha256.convert(bytes).toString();
|
||
|
|
}
|
||
|
|
|
||
|
|
static String hashFromBytes(Uint8List bytes) {
|
||
|
|
return sha256.convert(bytes).toString();
|
||
|
|
}
|
||
|
|
|
||
|
|
static String hashFromString(String input) {
|
||
|
|
return sha256.convert(utf8.encode(input)).toString();
|
||
|
|
}
|
||
|
|
|
||
|
|
static bool isValidHash(String hash) {
|
||
|
|
if (hash.length != 64) return false;
|
||
|
|
return RegExp(r'^[a-f0-9]{64}$').hasMatch(hash);
|
||
|
|
}
|
||
|
|
|
||
|
|
static List<String> extractHashes(String text) {
|
||
|
|
final regex = RegExp(r'[a-f0-9]{64}');
|
||
|
|
return regex.allMatches(text).map((m) => m.group(0)!).toList();
|
||
|
|
}
|
||
|
|
|
||
|
|
static String truncateHash(String hash, {int length = 8}) {
|
||
|
|
if (hash.length <= length) return hash;
|
||
|
|
return '${hash.substring(0, length)}...';
|
||
|
|
}
|
||
|
|
}
|