25-2/24/1

This commit is contained in:
Hamza-Ayed
2025-02-24 23:38:01 +03:00
parent 5f53461b34
commit d41314cfed
64 changed files with 1180 additions and 494 deletions

View File

@@ -1,34 +1,50 @@
import 'package:encrypt/encrypt.dart' as encrypt;
import 'package:flutter/foundation.dart';
import '../../env/env.dart';
var secretKey = Env.keyOfApp
.toString()
.split('XrXlBl')[0]; // Must be 16 characters for AES-128
String initializationVector = Env.initializationVector; // Must be 16 characters
final encryptionHelper = EncryptionHelper(
secretKey: secretKey,
initializationVector: initializationVector,
);
import '../../constant/box_name.dart';
import '../../main.dart';
class EncryptionHelper {
final encrypt.Key key;
final encrypt.IV iv;
static EncryptionHelper? _instance;
EncryptionHelper(
{required String secretKey, required String initializationVector})
: key = encrypt.Key.fromUtf8(secretKey),
iv = encrypt.IV.fromUtf8(initializationVector);
late final encrypt.Key key;
late final encrypt.IV iv;
// Initialize the helper
EncryptionHelper._(this.key, this.iv);
static EncryptionHelper get instance {
if (_instance == null) {
throw Exception(
"EncryptionHelper is not initialized. Call `await EncryptionHelper.initialize()` in main.");
}
return _instance!;
}
/// Encrypts the given plain text
/// Initializes and stores the instance globally
static Future<void> initialize() async {
if (_instance != null) {
debugPrint("EncryptionHelper is already initialized.");
return; // Prevent re-initialization
}
debugPrint("Initializing EncryptionHelper...");
// Read stored keys
String? keyOfApp = await storage.read(key: BoxName.keyOfApp);
// Log.print('keyOfApp: ${keyOfApp}');
String? initializationVector =
await storage.read(key: BoxName.initializationVector);
// Log.print('initializationVector: ${initializationVector}');
// Set the global instance
_instance = EncryptionHelper._(
encrypt.Key.fromUtf8(keyOfApp!),
encrypt.IV.fromUtf8(initializationVector!),
);
debugPrint("EncryptionHelper initialized successfully.");
}
/// Encrypts a string
String encryptData(String plainText) {
try {
final encrypter = encrypt.Encrypter(encrypt.AES(key,
mode: encrypt.AESMode.cbc)); // Explicitly use CBC mode
final encrypter =
encrypt.Encrypter(encrypt.AES(key, mode: encrypt.AESMode.cbc));
final encrypted = encrypter.encrypt(plainText, iv: iv);
return encrypted.base64;
} catch (e) {
@@ -37,14 +53,13 @@ class EncryptionHelper {
}
}
/// Decrypts the given encrypted text
/// Decrypts a string
String decryptData(String encryptedText) {
try {
final encrypter = encrypt.Encrypter(encrypt.AES(key,
mode: encrypt.AESMode.cbc)); // Explicitly use CBC mode
final encrypter =
encrypt.Encrypter(encrypt.AES(key, mode: encrypt.AESMode.cbc));
final encrypted = encrypt.Encrypted.fromBase64(encryptedText);
final decrypted = encrypter.decrypt(encrypted, iv: iv);
return decrypted;
return encrypter.decrypt(encrypted, iv: iv);
} catch (e) {
debugPrint('Decryption Error: $e');
return '';