Files
2026-10-26 20:48:16 +01:00

50 lines
1.8 KiB
Dart

import 'dart:convert';
import 'package:cryptography/cryptography.dart';
/// Encrypts/decrypts the club data (contacts) with the club code as the key,
/// so the data can ship inside the public app but is unreadable without the code.
///
/// No Flutter imports: also used by tool/encrypt_club_data.dart.
/// File format (assets/club.enc): JSON {v, salt, nonce, cipher, mac}, base64 values.
class ClubCrypto {
static const int _iterations = 100000;
static final _aes = AesGcm.with256bits();
/// Codes are compared ignoring case and surrounding spaces.
static String normalize(String code) => code.trim().toLowerCase();
static Future<SecretKey> _deriveKey(String code, List<int> salt) {
return Pbkdf2(macAlgorithm: Hmac.sha256(), iterations: _iterations, bits: 256)
.deriveKeyFromPassword(password: normalize(code), nonce: salt);
}
static Future<String> encrypt(String plaintext, String code) async {
final salt = SecretKeyData.random(length: 16).bytes;
final key = await _deriveKey(code, salt);
final box = await _aes.encrypt(utf8.encode(plaintext), secretKey: key);
return jsonEncode({
'v': 1,
'salt': base64Encode(salt),
'nonce': base64Encode(box.nonce),
'cipher': base64Encode(box.cipherText),
'mac': base64Encode(box.mac.bytes),
});
}
/// Returns the plaintext, or null if the code is wrong.
static Future<String?> decrypt(String encrypted, String code) async {
final data = jsonDecode(encrypted) as Map<String, dynamic>;
final key = await _deriveKey(code, base64Decode(data['salt']));
final box = SecretBox(
base64Decode(data['cipher']),
nonce: base64Decode(data['nonce']),
mac: Mac(base64Decode(data['mac'])),
);
try {
return utf8.decode(await _aes.decrypt(box, secretKey: key));
} on SecretBoxAuthenticationError {
return null;
}
}
}