To enhance your Flutter application by incorporating AES-256 encryption with a random Initialization Vector (IV) alongside your existing character shift cipher, you'll need to make several adjustments. Here's a step-by-step guide to achieve this:
- Add Necessary Dependencies
- Update the
Cipher Class
- Modify the Encryption and Decryption Methods
- Handle Key Management and IV Storage
Let's go through each step in detail.
1. Add Necessary Dependencies
To implement AES-256 encryption in Flutter, we'll use the encrypt package, which provides a simple interface for encryption and decryption. Additionally, ensure that you have the pointycastle package as it's a dependency for encrypt.
Update pubspec.yaml
Add the following dependencies to your pubspec.yaml file:
dependencies:
flutter:
sdk: flutter
encrypt: ^5.1.0
pointycastle: ^3.4.0
file_picker: ^5.2.2
shared_preferences: ^2.0.15
Note: Ensure you run flutter pub get after updating the pubspec.yaml to fetch the new packages.
2. Update the Cipher Class
We'll enhance the existing Cipher class to include AES-256 encryption with a random IV. The encrypted message will include both the IV and the ciphertext, concatenated and encoded in base64 for safe storage and transmission. Additionally, we'll append the user-provided key and apply the existing character shift.
Updated Cipher Class
import 'dart:convert';
import 'dart:math';
import 'package:encrypt/encrypt.dart';
class Cipher {
/// Verilen mesajı ve anahtarı kullanarak mesajı AES-256 ve karakter kaydırma ile şifreler
static String encrypt(String message, String key) {
// Validate Inputs
_validateInputs(key, message);
// Step 1: AES-256 Encryption with Random IV
final keyBytes = _generateAESKey(key);
final iv = IV.fromSecureRandom(16); // 128-bit IV for AES
final encrypter = Encrypter(AES(keyBytes, mode: AESMode.cbc));
final encrypted = encrypter.encrypt(message, iv: iv);
// Combine IV and Encrypted Data
String combined = base64UrlEncode(iv.bytes) + ':' + encrypted.base64;
// Step 2: Apply Character Shift
String shifted = _shiftText(combined, key);
return shifted;
}
/// Verilen şifreli mesajı ve anahtarı kullanarak mesajı AES-256 ve karakter kaydırma ile çözer
static String decrypt(String encryptedMessage, String key) {
// Validate Inputs
_validateInputs(key, encryptedMessage);
// Step 1: Reverse Character Shift
String unshifted = _shiftText(encryptedMessage, key, decrypt: true);
// Split IV and Encrypted Data
List<String> parts = unshifted.split(':');
if (parts.length != 2) {
throw Exception("Geçersiz şifreli mesaj formatı.");
}
IV iv;
Encrypted encrypted;
try {
iv = IV(base64Url.decode(parts[0]));
encrypted = Encrypted(base64Url.decode(parts[1]));
} catch (e) {
throw Exception("Şifreli mesaj çözülürken hata oluştu.");
}
// Step 2: AES-256 Decryption
final keyBytes = _generateAESKey(key);
final encrypter = Encrypter(AES(keyBytes, mode: AESMode.cbc));
String decrypted;
try {
decrypted = encrypter.decrypt(encrypted, iv: iv);
} catch (e) {
throw Exception("Şifre çözme işlemi başarısız. Anahtar yanlış olabilir.");
}
// Apply Existing Character Shift to Decrypted Message
String finalMessage = _shiftText(decrypted, key, decrypt: true);
return finalMessage;
}
/// Validates the key and message inputs
static void _validateInputs(String key, String message) {
if (key.isEmpty) {
throw Exception("Anahtar boş olamaz.");
}
if (!RegExp(r'^\d+$').hasMatch(key)) {
throw Exception("Anahtar sadece rakamlardan oluşmalıdır.");
}
if (message.isEmpty) {
throw Exception("Mesaj boş olamaz.");
}
}
/// Generates a 32-byte AES key from the provided key string
static Key _generateAESKey(String key) {
// Convert the numeric key string to bytes
// For simplicity, we'll pad or trim the key to fit 32 bytes
String paddedKey = key.padRight(32, '0').substring(0, 32);
return Key.fromUtf8(paddedKey);
}
/// Applies a Caesar-like shift to the text based on the key
/// If decrypt is true, it shifts in the opposite direction
static String _shiftText(String text, String key, {bool decrypt = false}) {
String shifted = '';
int keyLength = key.length;
for (int i = 0; i < text.length; i++) {
String char = text[i];
int shift = int.tryParse(key[i % keyLength]) ?? 0;
if (decrypt) {
shift = -shift;
}
// Shift only printable ASCII characters (32 to 126)
if (char.codeUnitAt(0) >= 32 && char.codeUnitAt(0) <= 126) {
int newCode = text.codeUnitAt(i) + shift;
if (newCode > 126) {
newCode = 32 + (newCode - 127);
} else if (newCode < 32) {
newCode = 127 - (32 - newCode);
}
shifted += String.fromCharCode(newCode);
} else {
// Non-printable characters remain unchanged
shifted += char;
}
}
return shifted;
}
}
Explanation of Changes
-
Dependencies:
- Imported
encrypt package classes for AES encryption and decryption.
- Imported
dart:convert for base64 encoding and decoding.
-
AES Encryption:
- Generated a 256-bit AES key by padding/trimming the user-provided numeric key to 32 bytes.
- Generated a random 128-bit IV for each encryption operation.
- Used AES encryption in CBC mode.
-
Combining IV and Encrypted Data:
- Concatenated the base64-encoded IV and ciphertext with a colon (
:) separator for storage.
-
Character Shift:
- Applied a Caesar-like shift to the combined IV and ciphertext using the user-provided key.
- Implemented a reverse shift during decryption.
-
Decryption Process:
- Reversed the character shift.
- Extracted the IV and ciphertext from the decrypted string.
- Performed AES decryption using the extracted IV and generated key.
- Applied reverse character shift to the decrypted message.
3. Modify the Encryption and Decryption Methods
Now, update the _encryptMessage and _decryptMessage methods in your _HomePageState class to use the new Cipher class.
Updated _HomePageState Class
class _HomePageState extends State<HomePage> {
// Kontrolörler
final TextEditingController _keyController = TextEditingController();
final TextEditingController _messageController = TextEditingController();
// Sonuç metni
String _result = "";
// Anahtar metninin gizli olup olmadığını kontrol eden değişken
bool _obscureKey = true;
/// Mesajı şifreler
void _encryptMessage() {
try {
String key = _keyController.text.trim();
String message = _messageController.text;
_validateInputs(key, message);
setState(() {
_result = Cipher.encrypt(message, key);
});
} catch (e) {
String error = e.toString().replaceAll('Exception: ', '');
_showError(error);
}
}
/// Mesajı çözer
void _decryptMessage() {
try {
String key = _keyController.text.trim();
String encryptedMessage = _messageController.text;
_validateInputs(key, encryptedMessage);
setState(() {
_result = Cipher.decrypt(encryptedMessage, key);
});
} catch (e) {
String error = e.toString().replaceAll('Exception: ', '');
_showError(error);
}
}
/// Kullanıcı girdilerini doğrular
void _validateInputs(String key, String message) {
if (key.isEmpty) {
throw Exception("Anahtar boş olamaz.");
}
if (!RegExp(r'^\d+$').hasMatch(key)) {
throw Exception("Anahtar sadece rakamlardan oluşmalıdır.");
}
if (message.isEmpty) {
throw Exception("Mesaj boş olamaz.");
}
}
// ... (rest of the class remains unchanged)
}
Explanation of Changes
- Encryption: Now uses the updated
Cipher.encrypt method, which implements AES-256 with a random IV and character shifting.
- Decryption: Similarly uses the updated
Cipher.decrypt method to reverse the encryption process.
4. Handle Key Management and IV Storage
To ensure security, it's crucial to manage keys and IVs properly. In the updated Cipher class:
-
Key Management: The user-provided numeric key is transformed into a 32-byte AES key by padding or trimming. This approach ensures that even short numeric keys are expanded to meet AES-256 requirements. However, for enhanced security, consider allowing users to provide more complex keys or implementing a key derivation function (e.g., PBKDF2) to generate cryptographically secure keys from user inputs.
-
IV Storage: The IV is generated randomly for each encryption operation and stored alongside the ciphertext, separated by a colon (:). Both are base64-encoded to ensure safe transmission and storage.
Full Updated Code
Below is the complete updated code integrating all the changes mentioned above:
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:file_picker/file_picker.dart';
import 'package:shared_preferences/shared_preferences.dart';
import 'dart:io';
import 'dart:convert';
import 'dart:math';
import 'package:encrypt/encrypt.dart';
void main() {
runApp(EncryptionApp());
}
/// Uygulamanın ana widget'ı
class EncryptionApp extends StatefulWidget {
@override
_EncryptionAppState createState() => _EncryptionAppState();
}
class _EncryptionAppState extends State<EncryptionApp> {
bool _agreedToTerms = false;
bool _loading = true;
// Temalar (lightTheme ve darkTheme önceki gibi tanımlanmış)
/// Uygulamanın ana widget'ı
// Açık tema tanımı
final ThemeData lightTheme = ThemeData(
brightness: Brightness.light,
primarySwatch: Colors.teal,
scaffoldBackgroundColor: Colors.grey[100],
textTheme: TextTheme(
bodyMedium: TextStyle(fontSize: 16),
),
appBarTheme: AppBarTheme(
backgroundColor: Colors.teal[700],
foregroundColor: Colors.white,
titleTextStyle: TextStyle(fontWeight: FontWeight.w900, fontSize: 24)),
elevatedButtonTheme: ElevatedButtonThemeData(
style: ElevatedButton.styleFrom(
backgroundColor: Colors.white,
foregroundColor: Colors.teal[600],
textStyle: TextStyle(fontSize: 16),
),
),
inputDecorationTheme: InputDecorationTheme(
border: OutlineInputBorder(),
prefixIconColor: Colors.teal,
suffixIconColor: Colors.teal,
),
);
// Koyu tema tanımı
final ThemeData darkTheme = ThemeData(
brightness: Brightness.dark,
primarySwatch: Colors.teal,
textTheme: TextTheme(
bodyMedium: TextStyle(fontSize: 16),
),
appBarTheme: AppBarTheme(
backgroundColor: Colors.teal[900],
titleTextStyle: TextStyle(fontWeight: FontWeight.bold)),
elevatedButtonTheme: ElevatedButtonThemeData(
style: ElevatedButton.styleFrom(
backgroundColor: Colors.white,
foregroundColor: Colors.teal[800],
textStyle: TextStyle(fontSize: 16),
),
),
inputDecorationTheme: InputDecorationTheme(
border: OutlineInputBorder(),
prefixIconColor: Colors.teal[200],
suffixIconColor: Colors.teal[200],
),
);
@override
void initState() {
super.initState();
_checkAgreement();
}
/// Kullanıcının kullanım koşullarını onaylayıp onaylamadığını kontrol eder
void _checkAgreement() async {
SharedPreferences prefs = await SharedPreferences.getInstance();
bool agreed = prefs.getBool('agreedToTerms') ?? false;
setState(() {
_agreedToTerms = agreed;
_loading = false;
});
}
@override
Widget build(BuildContext context) {
// Yükleme ekranı
if (_loading) {
return MaterialApp(
debugShowCheckedModeBanner: false,
home: Scaffold(
body: Center(child: CircularProgressIndicator()),
),
);
}
return MaterialApp(
debugShowCheckedModeBanner: false,
title: 'Kriptolog',
theme: lightTheme, // Açık tema
darkTheme: darkTheme, // Koyu tema
themeMode: ThemeMode.system, // Sistem ayarlarına bağlı tema modu
home: _agreedToTerms ? HomePage() : TermsAndConditionsPage(),
);
}
}
/// Kullanım koşulları sayfası
class TermsAndConditionsPage extends StatefulWidget {
@override
_TermsAndConditionsPageState createState() =>
_TermsAndConditionsPageState();
}
class _TermsAndConditionsPageState extends State<TermsAndConditionsPage> {
/// Kullanıcının kullanım koşullarını kabul etmesini işler
void _acceptTerms() async {
SharedPreferences prefs = await SharedPreferences.getInstance();
await prefs.setBool('agreedToTerms', true);
// Ana sayfaya yönlendir
Navigator.pushReplacement(
context,
MaterialPageRoute(builder: (context) => HomePage()),
);
}
/// Kullanıcının kullanım koşullarını reddetmesini işler
void _declineTerms() {
// Uygulamadan çık
Navigator.pop(context);
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text('Dikkat'),
automaticallyImplyLeading: false, // Geri butonunu kaldırır
),
body: Padding(
padding: const EdgeInsets.all(20.0),
child: SingleChildScrollView(
// İçeriğin taşması durumunda kaydırılmasını sağlar
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
// Kullanım Koşulları Başlığı
Text(
'Bilgilendirme',
style: TextStyle(
fontSize: 22,
fontWeight: FontWeight.bold,
),
),
SizedBox(height: 20),
// Kullanım Koşulları Metni
Text(
'Anahtarınız, mesajlarınızın güvenliği için çok önemlidir. Lütfen anahtarınızı kimseyle paylaşmayın ve güvenli bir yerde saklayın.\n\n'
'Eğer anahtarınızı unutursanız, şifrelenmiş mesajlarınızı çözemezsiniz ve geri getirmeniz mümkün olmaz. Bu nedenle anahtarınızı güvenli bir yerde saklamayı unutmayın.\n\n'
'Bu uygulama, girdiğiniz mesajı ve anahtarı kullanarak mesajınızı şifreler veya çözer. Harfler ve sayılar anahtarınıza göre kaydırılır. Şifreleme ve çözme işlemleri için aynı anahtarı kullanmanız gerekmektedir.',
),
SizedBox(height: 30),
// Kabul ve Reddet Butonları
Center(
child: ElevatedButton(
onPressed: _acceptTerms,
child: Text('Tamamdır..'),
),
),
// Row(
// mainAxisAlignment: MainAxisAlignment.center,
// children: [
// ElevatedButton(
// onPressed: _acceptTerms,
// child: Text('Tamamdır..'),
// style: ElevatedButton.styleFrom(
// padding:
// EdgeInsets.symmetric(horizontal: 40, vertical: 15),
// ),
// ),
// SizedBox(width: 20),
// TextButton(
// onPressed: _declineTerms,
// child: Text('Reddet'),
// style: TextButton.styleFrom(
// padding:
// EdgeInsets.symmetric(horizontal: 40, vertical: 15),
// ),
// ),
// ],
// ),
],
),
),
),
);
}
}
/// Ana sayfa widget'ı
class HomePage extends StatefulWidget {
@override
_HomePageState createState() => _HomePageState();
}
/// Ana sayfa durumu
class _HomePageState extends State<HomePage> {
// Kontrolörler
final TextEditingController _keyController = TextEditingController();
final TextEditingController _messageController = TextEditingController();
// Sonuç metni
String _result = "";
// Anahtar metninin gizli olup olmadığını kontrol eden değişken
bool _obscureKey = true;
/// Mesajı şifreler
void _encryptMessage() {
try {
String key = _keyController.text.trim();
String message = _messageController.text;
_validateInputs(key, message);
setState(() {
_result = Cipher.encrypt(message, key);
});
} catch (e) {
String error = e.toString().replaceAll('Exception: ', '');
_showError(error);
}
}
/// Mesajı çözer
void _decryptMessage() {
try {
String key = _keyController.text.trim();
String encryptedMessage = _messageController.text;
_validateInputs(key, encryptedMessage);
setState(() {
_result = Cipher.decrypt(encryptedMessage, key);
});
} catch (e) {
String error = e.toString().replaceAll('Exception: ', '');
_showError(error);
}
}
/// Kullanıcı girdilerini doğrular
void _validateInputs(String key, String message) {
if (key.isEmpty) {
throw Exception("Anahtar boş olamaz.");
}
if (!RegExp(r'^\d+$').hasMatch(key)) {
throw Exception("Anahtar sadece rakamlardan oluşmalıdır.");
}
if (message.isEmpty) {
throw Exception("Mesaj boş olamaz.");
}
}
/// Dosya seçer ve mesaj alanına yükler
Future<void> _pickFile() async {
try {
FilePickerResult? result = await FilePicker.platform.pickFiles();
if (result != null) {
File file = File(result.files.single.path!);
String contents = await file.readAsString();
if (contents.length > 10000) {
throw Exception(
"Dosya çok büyük. Maksimum 10.000 karaktere izin verilmektedir.");
}
setState(() {
_messageController.text = contents;
});
} else {
// Kullanıcı dosya seçmedi, işlem iptal edildi.
}
} catch (e) {
String error = e.toString().replaceAll('Exception: ', '');
_showError(error);
}
}
/// Hata mesajlarını snackbar ile gösterir
void _showError(String message) {
ScaffoldMessenger.of(context).showSnackBar(
SnackBar(
content: Text(message),
backgroundColor: Colors.redAccent,
),
);
}
@override
void initState() {
super.initState();
_messageController.addListener(_onMessageChanged);
}
void _onMessageChanged() {
setState(() {
// Arayüzü güncellemek için
});
}
@override
void dispose() {
// Kontrolörleri serbest bırakır
_keyController.dispose();
_messageController.removeListener(_onMessageChanged);
_messageController.dispose();
super.dispose();
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text('Kriptolog'),
actions: [
IconButton(
icon: Icon(Icons.info_outline),
onPressed: () {
// Bilgi sayfasına geçiş yapar
Navigator.push(
context,
MaterialPageRoute(builder: (context) => InfoPage()),
);
},
),
],
),
body: Padding(
padding: const EdgeInsets.all(20.0),
child: SingleChildScrollView(
// İçeriğin taşması durumunda kaydırma yapmaya olanak tanır
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
// Anahtar Girişi
TextField(
controller: _keyController,
decoration: InputDecoration(
labelText: 'Anahtar',
border: OutlineInputBorder(),
prefixIcon: Icon(Icons.vpn_key),
suffixIcon: IconButton(
icon: Icon(
_obscureKey ? Icons.visibility : Icons.visibility_off,
),
onPressed: () {
setState(() {
_obscureKey = !_obscureKey;
});
},
),
),
obscureText: _obscureKey, // Metni gizler veya gösterir
keyboardType: TextInputType.number,
),
SizedBox(height: 20),
// Mesaj Girişi
TextField(
controller: _messageController,
decoration: InputDecoration(
labelText: 'Mesaj',
border: OutlineInputBorder(),
prefixIcon: Icon(Icons.message),
suffixIcon: _messageController.text.isNotEmpty
? IconButton(
icon: Icon(Icons.clear),
tooltip: 'Mesajı temizle',
onPressed: () {
_messageController.clear();
},
)
: null,
),
maxLines: null,
),
SizedBox(height: 20),
// Butonlar
Row(
children: [
Expanded(
child: ElevatedButton.icon(
onPressed: _encryptMessage,
icon: Icon(Icons.lock),
label: Text('Şifrele'),
style: ElevatedButton.styleFrom(
padding: EdgeInsets.symmetric(vertical: 15),
),
),
),
SizedBox(width: 10),
Expanded(
child: ElevatedButton.icon(
onPressed: _decryptMessage,
icon: Icon(Icons.lock_open),
label: Text('Çöz'),
style: ElevatedButton.styleFrom(
padding: EdgeInsets.symmetric(vertical: 15),
),
),
),
],
),
SizedBox(height: 10),
ElevatedButton.icon(
onPressed: _pickFile,
icon: Icon(Icons.upload_file),
label: Text('Dosya Yükle'),
style: ElevatedButton.styleFrom(
padding: EdgeInsets.symmetric(vertical: 15),
minimumSize: Size(double.infinity, 50),
),
),
SizedBox(height: 20),
// Sonuç Gösterimi
_result.isNotEmpty
? ResultCard(
result: _result,
onClear: () {
setState(() {
_result = '';
});
},
)
: SizedBox(),
],
),
),
),
);
}
}
/// Uyarı ve Bilgi mesajlarını içeren sayfa
class InfoPage extends StatelessWidget {
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text('Bilgi'),
),
body: Padding(
padding: const EdgeInsets.all(20.0),
child: SingleChildScrollView(
// İçeriğin taşması durumunda kaydırılmasını sağlar
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
// Uyarı Başlığı
Text(
'Anahtarınızı Paylaşmayın ve Unutmayın',
style: TextStyle(
fontSize: 20,
fontWeight: FontWeight.bold,
),
),
SizedBox(height: 10),
// Uyarı Metni
Text(
'Anahtarınız, mesajlarınızın güvenliği için çok önemlidir. Lütfen anahtarınızı kimseyle paylaşmayın ve güvenli bir yerde saklayın.',
),
SizedBox(height: 20),
// Anahtar Unutma Başlığı
Text(
'Anahtarınızı Unutursanız',
style: TextStyle(
fontSize: 20,
fontWeight: FontWeight.bold,
),
),
SizedBox(height: 10),
// Anahtar Unutma Metni
Text(
'Eğer anahtarınızı unutursanız, şifrelenmiş mesajlarınızı çözemezsiniz ve geri getirmeniz mümkün olmaz. Bu nedenle anahtarınızı güvenli bir yerde saklamayı unutmayın.',
),
SizedBox(height: 20),
// Uygulama Çalışma Mantığı Başlığı
Text(
'Uygulamanın Çalışma Mantığı',
style: TextStyle(
fontSize: 20,
fontWeight: FontWeight.bold,
),
),
SizedBox(height: 10),
// Uygulama Çalışma Mantığı Metni
Text(
'Bu uygulama, girdiğiniz mesajı ve anahtarı kullanarak mesajınızı şifreler veya çözer. Harfler ve sayılar anahtarınıza göre kaydırılır. Şifreleme ve çözme işlemleri için aynı anahtarı kullanmanız gerekmektedir.',
),
],
),
),
),
);
}
}
/// Şifrelenmiş veya çözülmüş mesajı gösteren kart widget'ı
class ResultCard extends StatelessWidget {
final String result;
final VoidCallback onClear;
ResultCard({required this.result, required this.onClear});
@override
Widget build(BuildContext context) {
return Card(
elevation: 2,
color: Theme.of(context).cardColor, // Temaya göre kart rengi
child: Padding(
padding: const EdgeInsets.all(10.0),
child: Column(
children: [
// Toolbar
Row(
mainAxisAlignment: MainAxisAlignment.spaceBetween,
children: [
Text(
'Sonuç:',
style: TextStyle(
fontWeight: FontWeight.bold,
fontSize: 18,
color: Theme.of(context).textTheme.bodyLarge?.color,
),
),
// İkon butonlarını içeren yeni bir satır ekleyelim
Row(
children: [
// Kopyalama ikon butonu
IconButton(
icon: Icon(Icons.copy),
onPressed: () {
// Sonucu panoya kopyala
Clipboard.setData(ClipboardData(text: result));
// Kullanıcıya geri bildirim ver
ScaffoldMessenger.of(context).showSnackBar(
SnackBar(
content: Text('Sonuç panoya kopyalandı'),
),
);
},
),
// Temizleme ikon butonu (mevcut)
IconButton(
icon: Icon(Icons.delete),
onPressed: onClear,
),
],
),
],
),
SizedBox(height: 5),
// Sonuç Metni
Align(
alignment: Alignment.centerLeft,
child: SelectableText(
result,
style: TextStyle(
fontSize: 16,
color: Theme.of(context).textTheme.bodyLarge?.color,
),
),
),
],
),
),
);
}
}
/// Şifreleme ve çözme işlemlerini gerçekleştiren sınıf
class Cipher {
/// Verilen mesajı ve anahtarı kullanarak mesajı AES-256 ve karakter kaydırma ile şifreler
static String encrypt(String message, String key) {
// Validate Inputs
_validateInputs(key, message);
// Step 1: AES-256 Encryption with Random IV
final keyBytes = _generateAESKey(key);
final iv = IV.fromSecureRandom(16); // 128-bit IV for AES
final encrypter = Encrypter(AES(keyBytes, mode: AESMode.cbc));
final encrypted = encrypter.encrypt(message, iv: iv);
// Combine IV and Encrypted Data
String combined = base64UrlEncode(iv.bytes) + ':' + encrypted.base64;
// Step 2: Apply Character Shift
String shifted = _shiftText(combined, key);
return shifted;
}
/// Verilen şifreli mesajı ve anahtarı kullanarak mesajı AES-256 ve karakter kaydırma ile çözer
static String decrypt(String encryptedMessage, String key) {
// Validate Inputs
_validateInputs(key, encryptedMessage);
// Step 1: Reverse Character Shift
String unshifted = _shiftText(encryptedMessage, key, decrypt: true);
// Split IV and Encrypted Data
List<String> parts = unshifted.split(':');
if (parts.length != 2) {
throw Exception("Geçersiz şifreli mesaj formatı.");
}
IV iv;
Encrypted encrypted;
try {
iv = IV(base64Url.decode(parts[0]));
encrypted = Encrypted(base64Url.decode(parts[1]));
} catch (e) {
throw Exception("Şifreli mesaj çözülürken hata oluştu.");
}
// Step 2: AES-256 Decryption
final keyBytes = _generateAESKey(key);
final encrypter = Encrypter(AES(keyBytes, mode: AESMode.cbc));
String decrypted;
try {
decrypted = encrypter.decrypt(encrypted, iv: iv);
} catch (e) {
throw Exception("Şifre çözme işlemi başarısız. Anahtar yanlış olabilir.");
}
// Apply Existing Character Shift to Decrypted Message
String finalMessage = _shiftText(decrypted, key, decrypt: true);
return finalMessage;
}
/// Validates the key and message inputs
static void _validateInputs(String key, String message) {
if (key.isEmpty) {
throw Exception("Anahtar boş olamaz.");
}
if (!RegExp(r'^\d+$').hasMatch(key)) {
throw Exception("Anahtar sadece rakamlardan oluşmalıdır.");
}
if (message.isEmpty) {
throw Exception("Mesaj boş olamaz.");
}
}
/// Generates a 32-byte AES key from the provided key string
static Key _generateAESKey(String key) {
// Convert the numeric key string to bytes
// For simplicity, we'll pad or trim the key to fit 32 bytes
String paddedKey = key.padRight(32, '0').substring(0, 32);
return Key.fromUtf8(paddedKey);
}
/// Applies a Caesar-like shift to the text based on the key
/// If decrypt is true, it shifts in the opposite direction
static String _shiftText(String text, String key, {bool decrypt = false}) {
String shifted = '';
int keyLength = key.length;
for (int i = 0; i < text.length; i++) {
String char = text[i];
int shift = int.tryParse(key[i % keyLength]) ?? 0;
if (decrypt) {
shift = -shift;
}
// Shift only printable ASCII characters (32 to 126)
if (char.codeUnitAt(0) >= 32 && char.codeUnitAt(0) <= 126) {
int newCode = text.codeUnitAt(i) + shift;
if (newCode > 126) {
newCode = 32 + (newCode - 127);
} else if (newCode < 32) {
newCode = 127 - (32 - newCode);
}
shifted += String.fromCharCode(newCode);
} else {
// Non-printable characters remain unchanged
shifted += char;
}
}
return shifted;
}
}
Additional Recommendations
-
Key Strength: Relying solely on numeric keys can be insecure, especially for AES encryption. Consider allowing users to input alphanumeric keys and using a key derivation function like PBKDF2 to generate secure keys from user inputs.
-
Error Handling: Enhance error messages to be more user-friendly and considerate of security implications. Avoid exposing sensitive error details.
-
Security Best Practices: Ensure that cryptographic operations are performed securely. Avoid custom cryptographic solutions unless necessary, and prefer well-established libraries and protocols.
-
User Experience: Inform users about the importance of remembering their keys, as losing them would make it impossible to decrypt their messages.
-
Testing: Thoroughly test the encryption and decryption processes to ensure data integrity and security.
By following the above steps, your Flutter application will now use AES-256 encryption with a random IV, combined with your existing character shift cipher, enhancing the security of the encrypted messages.