Data Encryption

Protect sensitive data in your Flutter app

🔒 What is Data Encryption?

Data encryption converts readable information into coded format to prevent unauthorized access. Flutter apps use encryption algorithms to protect sensitive user data like passwords, personal information, and payment details from security threats.


// Encrypt sensitive data
final encrypted = encrypter.encrypt(plainText, iv: iv);
final decrypted = encrypter.decrypt(encrypted, iv: iv);
                                    

Key Encryption Concepts

🔐

AES Encryption

Advanced Encryption Standard for securing data with symmetric key encryption algorithm

final encrypter = Encrypter(
  AES(key)
);
🔑

Encryption Key

Secret key used to encrypt and decrypt data securely in your application

final key = Key.fromLength(32);
🎲

IV (Initialization Vector)

Random value that ensures same data encrypts differently each time for security

final iv = IV.fromLength(16);
🔓

Decryption

Convert encrypted data back to original readable format using the encryption key

encrypter.decrypt(
  encrypted, iv: iv
);

🔹 Setup Encryption Package

Add the encrypt package to your Flutter project:

# pubspec.yaml
dependencies:
  encrypt: ^5.0.3
// Import the package
import 'package:encrypt/encrypt.dart';

Result:

Encryption library is ready to use in your Flutter app.

🔹 Basic AES Encryption

Encrypt and decrypt text using AES algorithm:

import 'package:encrypt/encrypt.dart';

class EncryptionService {
  // Generate a secure key (32 bytes for AES-256)
  final key = Key.fromUtf8('my32lengthsupersecretnooneknows1');
  
  // Generate initialization vector
  final iv = IV.fromLength(16);

  String encryptData(String plainText) {
    final encrypter = Encrypter(AES(key));
    final encrypted = encrypter.encrypt(plainText, iv: iv);
    return encrypted.base64;
  }

  String decryptData(String encryptedText) {
    final encrypter = Encrypter(AES(key));
    final decrypted = encrypter.decrypt64(encryptedText, iv: iv);
    return decrypted;
  }
}

Result:

Text is encrypted into unreadable format and can be decrypted back to original.

🔹 Encrypt User Password

Securely encrypt passwords before storing:

class PasswordEncryption {
  final key = Key.fromUtf8('my32lengthsupersecretnooneknows1');
  final iv = IV.fromLength(16);

  Future encryptPassword(String password) async {
    final encrypter = Encrypter(AES(key));
    final encrypted = encrypter.encrypt(password, iv: iv);
    return encrypted.base64;
  }

  Future decryptPassword(String encryptedPassword) async {
    final encrypter = Encrypter(AES(key));
    final decrypted = encrypter.decrypt64(encryptedPassword, iv: iv);
    return decrypted;
  }
}

// Usage
final service = PasswordEncryption();
String encrypted = await service.encryptPassword('myPassword123');
print('Encrypted: $encrypted');

Result:

Password is encrypted before storage, protecting it from unauthorized access.

🔹 Generate Secure Keys

Create random encryption keys for better security:

import 'package:encrypt/encrypt.dart';
import 'dart:math';

class KeyGenerator {
  // Generate random secure key
  static Key generateKey() {
    final random = Random.secure();
    final values = List.generate(32, (i) => random.nextInt(256));
    return Key(Uint8List.fromList(values));
  }

  // Generate random IV
  static IV generateIV() {
    final random = Random.secure();
    final values = List.generate(16, (i) => random.nextInt(256));
    return IV(Uint8List.fromList(values));
  }
}

// Usage
final key = KeyGenerator.generateKey();
final iv = KeyGenerator.generateIV();
print('Key: ${key.base64}');
print('IV: ${iv.base64}');

Result:

Random secure keys generated for encryption, different each time for maximum security.

🔹 Encrypt JSON Data

Encrypt complex data structures like JSON objects:

import 'dart:convert';

class JsonEncryption {
  final key = Key.fromUtf8('my32lengthsupersecretnooneknows1');
  final iv = IV.fromLength(16);

  String encryptJson(Map data) {
    final encrypter = Encrypter(AES(key));
    final jsonString = jsonEncode(data);
    final encrypted = encrypter.encrypt(jsonString, iv: iv);
    return encrypted.base64;
  }

  Map decryptJson(String encryptedData) {
    final encrypter = Encrypter(AES(key));
    final decrypted = encrypter.decrypt64(encryptedData, iv: iv);
    return jsonDecode(decrypted);
  }
}

// Usage
final service = JsonEncryption();
final userData = {'name': 'John', 'email': '[email protected]'};
String encrypted = service.encryptJson(userData);
Map decrypted = service.decryptJson(encrypted);

Result:

Complex user data encrypted as a whole, protecting all fields simultaneously.

🔹 Hash Passwords

Use hashing for one-way password protection:

import 'package:crypto/crypto.dart';
import 'dart:convert';

class PasswordHasher {
  // Hash password using SHA-256
  String hashPassword(String password) {
    final bytes = utf8.encode(password);
    final hash = sha256.convert(bytes);
    return hash.toString();
  }

  // Verify password
  bool verifyPassword(String password, String hashedPassword) {
    final hash = hashPassword(password);
    return hash == hashedPassword;
  }
}

// Usage
final hasher = PasswordHasher();
String hashed = hasher.hashPassword('myPassword123');
print('Hashed: $hashed');

bool isValid = hasher.verifyPassword('myPassword123', hashed);
print('Valid: $isValid');

Result:

Password converted to irreversible hash. Original password cannot be recovered from hash.

🧠 Test Your Knowledge

What does AES stand for in encryption?