marco.pms.mobileapp/lib/helpers/services/security_service.dart

41 lines
1.2 KiB
Dart

import 'dart:convert';
import 'package:cryptography/cryptography.dart';
class SecurityService {
// Same 32-byte key
static const _keyBase64 = "Your32ByteBase64KeyGoesHere/1234567890+XY=";
static Future<dynamic> decryptResponse(String encryptedBase64) async {
final algorithm = AesGcm.with256bits();
// 1. Decode Key and Data
final secretKey = await algorithm.newSecretKeyFromBytes(base64.decode(_keyBase64));
final encryptedBytes = base64.decode(encryptedBase64);
// 2. Extract Parts: [Nonce 12] + [Ciphertext] + [Tag 16]
// The "SecretBox" class helps us organize these parts
final nonce = encryptedBytes.sublist(0, 12);
final ciphertext = encryptedBytes.sublist(12, encryptedBytes.length - 16);
final mac = encryptedBytes.sublist(encryptedBytes.length - 16);
final secretBox = SecretBox(
ciphertext,
nonce: nonce,
mac: Mac(mac),
);
// 3. Decrypt
try {
final decryptedBytes = await algorithm.decrypt(
secretBox,
secretKey: secretKey,
);
final decryptedString = utf8.decode(decryptedBytes);
return json.decode(decryptedString);
} catch (e) {
print("Decryption failed: $e");
return null;
}
}
}