Files
service_intaleq/lib/controller/functions/encrypt_decrypt.dart
2026-05-02 15:12:46 +03:00

88 lines
2.4 KiB
Dart

import 'package:encrypt/encrypt.dart' as encrypt;
import 'package:flutter/foundation.dart';
import 'package:service/env/env.dart';
import 'package:secure_string_operations/secure_string_operations.dart';
import 'package:service/constant/char_map.dart';
import 'package:service/print.dart';
class EncryptionHelper {
static EncryptionHelper? _instance;
late final encrypt.Key key;
late final encrypt.IV iv;
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!;
}
/// 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 = r(Env.keyOfApp).toString().split(Env.addd)[0];
String initializationVector = r(Env.initializationVector).toString().split(Env.addd)[0];
Log.print('Key Length: ${keyOfApp.length}');
Log.print('IV Length: ${initializationVector.length}');
// 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) {
Log.print('Encrypting: $plainText');
try {
final encrypter =
encrypt.Encrypter(encrypt.AES(key, mode: encrypt.AESMode.cbc));
final encrypted = encrypter.encrypt(plainText, iv: iv);
return encrypted.base64;
} catch (e) {
Log.print('Encryption Error: $e');
return '';
}
}
/// Decrypts a string
String decryptData(String encryptedText) {
try {
final encrypter =
encrypt.Encrypter(encrypt.AES(key, mode: encrypt.AESMode.cbc));
final encrypted = encrypt.Encrypted.fromBase64(encryptedText);
return encrypter.decrypt(encrypted, iv: iv);
} catch (e) {
debugPrint('Decryption Error: $e');
return '';
}
}
}
r(String string) {
var res = X.r(X.r(X.r(string, cn), cC), cs).toString();
// Log.print('r($string) => $res');
return res;
}
c(String string) {
return X.c(X.c(X.c(string, cn), cC), cs).toString();
}