import 'package:encrypt/encrypt.dart' as enc; import 'package:crypto/crypto.dart'; import 'dart:convert'; import 'dart:typed_data'; class CryptoHelper { // این پیشوند باعث می‌شود بفهمیم پیام رمزدار است static const String prefix = "ENC:"; // تبدیل رمز ساده کاربر (مثلا 1234) به کلید امن ۳۲ بایتی static enc.Key _generateKey(String password) { var bytes = utf8.encode(password); var digest = sha256.convert(bytes); return enc.Key(Uint8List.fromList(digest.bytes)); } // متد رمزنگاری static String encrypt(String plainText, String password) { try { final key = _generateKey(password); final iv = enc.IV.fromLength(16); // تولید IV تصادفی final encrypter = enc.Encrypter(enc.AES(key)); final encrypted = encrypter.encrypt(plainText, iv: iv); // فرمت خروجی: ENC:IV_BASE64:MESSAGE_BASE64 return "$prefix${iv.base64}:${encrypted.base64}"; } catch (e) { print("Error creating encryption: $e"); return plainText; } } // متد رمزگشایی static String decrypt(String encryptedText, String password) { // اگر پیام پیشوند ما را نداشت، یعنی پیام معمولی است if (!encryptedText.startsWith(prefix)) return encryptedText; try { // جدا کردن بخش‌ها (حذف ENC و جدا کردن IV از متن) final parts = encryptedText.substring(4).split(':'); if (parts.length != 2) return "فرمت پیام نامعتبر است"; final iv = enc.IV.fromBase64(parts[0]); final cipherText = parts[1]; final key = _generateKey(password); final encrypter = enc.Encrypter(enc.AES(key)); return encrypter.decrypt64(cipherText, iv: iv); } catch (e) { return "⛔ رمز اشتباه است یا پیام مخدوش شده."; } } // متد کمکی برای تشخیص اینکه آیا پیام رمزدار است یا نه static bool isEncrypted(String text) { return text.startsWith(prefix); } }