flutter_security_provider 1.0.0 copy "flutter_security_provider: ^1.0.0" to clipboard
flutter_security_provider: ^1.0.0 copied to clipboard

A comprehensive Flutter package for AES encryption (GCM and CBC modes), key generation, and secure data handling with pointycastle.

example/lib/main.dart

import 'package:flutter/material.dart';
import 'package:flutter_security_provider/flutter_security_provider.dart';

void main() {
  runApp(const MyApp());
}

class MyApp extends StatelessWidget {
  const MyApp({super.key});

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Flutter Security Provider Example',
      theme: ThemeData(
        primarySwatch: Colors.blue,
        useMaterial3: true,
      ),
      home: const ExamplePage(),
    );
  }
}

class ExamplePage extends StatefulWidget {
  const ExamplePage({super.key});

  @override
  State<ExamplePage> createState() => _ExamplePageState();
}

class _ExamplePageState extends State<ExamplePage> {
  final List<String> _results = [];
  final ScrollController _scrollController = ScrollController();

  void _addResult(String result) {
    setState(() {
      _results.add(result);
    });
    // Auto scroll to bottom
    Future.delayed(const Duration(milliseconds: 100), () {
      if (_scrollController.hasClients) {
        _scrollController.animateTo(
          _scrollController.position.maxScrollExtent,
          duration: const Duration(milliseconds: 300),
          curve: Curves.easeOut,
        );
      }
    });
  }

  void _clearResults() {
    setState(() {
      _results.clear();
    });
  }

  void _demonstrateAesGcm() {
    _addResult('\n=== AES-GCM Encryption Demo ===');
    try {
      final encryptor = JsonAesGcmEncryptor(
        stringKey: 'my-super-secret-key-32-chars!!',
      );

      final jsonData = {
        'username': 'john_doe',
        'email': 'john@example.com',
        'timestamp': DateTime.now().toIso8601String(),
      };

      _addResult('Original data: $jsonData');

      final encrypted = encryptor.encryptJson(jsonData);
      _addResult('Encrypted: $encrypted');

      final decrypted = encryptor.decryptJson(encrypted);
      _addResult('Decrypted: $decrypted');
      _addResult('✅ AES-GCM encryption successful!');
    } catch (e) {
      _addResult('❌ Error: $e');
    }
  }

  void _demonstrateAesCbc() {
    _addResult('\n=== AES-CBC Encryption Demo ===');
    try {
      final encryptor = JsonAesCbcEncryptor(
        stringKey: '16-byte-key-here',
      );

      final jsonData = {
        'action': 'login',
        'userId': 12345,
        'sessionId': 'abc-def-ghi',
      };

      _addResult('Original data: $jsonData');

      final encrypted = encryptor.encryptJson(jsonData);
      _addResult('Encrypted: $encrypted');

      final decrypted = encryptor.decryptJson(encrypted);
      _addResult('Decrypted: $decrypted');
      _addResult('✅ AES-CBC encryption successful!');
    } catch (e) {
      _addResult('❌ Error: $e');
    }
  }

  void _demonstrateKeyGeneration() {
    _addResult('\n=== Key Generation Demo ===');
    try {
      const password = 'MySecurePassword123!';

      // Generate obfuscated key
      final obfuscatedKey = GeneradorClave.cifrarConSustitucion(password);
      _addResult('Password: $password');
      _addResult('Obfuscated key: $obfuscatedKey');

      // Generate 16-byte hash
      final keyBytes = GeneradorClave.hashTo16Bytes('mySecretKey');
      _addResult('16-byte hash length: ${keyBytes.length}');
      _addResult('✅ Key generation successful!');
    } catch (e) {
      _addResult('❌ Error: $e');
    }
  }

  void _demonstrateHmac() {
    _addResult('\n=== Time-based HMAC Demo ===');
    try {
      final body = {
        'userId': 12345,
        'action': 'update_profile',
        'timestamp': DateTime.now().millisecondsSinceEpoch,
      };

      final hmac = UtilFlutterSecurityProvider.createTimeBasedHMAC(
        body: body,
        key: 'my-hmac-secret-key',
        timeToSync: '0',
        validityInSeconds: '3600',
      );

      _addResult('Body: $body');
      _addResult('HMAC: $hmac');
      _addResult('✅ HMAC generation successful!');
    } catch (e) {
      _addResult('❌ Error: $e');
    }
  }

  void _demonstrateLoginToken() {
    _addResult('\n=== Login Token Generation Demo ===');
    try {
      const password = 'userPassword123';
      final timeSlot = DateTime.now().millisecondsSinceEpoch ~/ 1000;

      _addResult('Original password: $password');
      _addResult('Time slot: $timeSlot');

      final mixedPassword = GeneradorLoginPost.mezclarPalabra(
        password,
        timeSlot,
      );
      _addResult('Mixed password: $mixedPassword');

      final hashedToken = GeneradorLoginPost.calcularHashSha256(mixedPassword);
      _addResult('SHA-256 token: $hashedToken');
      _addResult('✅ Login token generation successful!');
    } catch (e) {
      _addResult('❌ Error: $e');
    }
  }

  void _demonstrateRandomIV() {
    _addResult('\n=== Random IV Generation Demo ===');
    try {
      final iv16 = UtilFlutterSecurityProvider.generateRandomIV(16);
      _addResult('16-byte IV: ${iv16.toString()}');
      _addResult('IV length: ${iv16.length}');

      final iv32 = UtilFlutterSecurityProvider.generateRandomIV(32);
      _addResult('32-byte IV length: ${iv32.length}');
      _addResult('✅ Random IV generation successful!');
    } catch (e) {
      _addResult('❌ Error: $e');
    }
  }

  void _runAllDemos() {
    _clearResults();
    _addResult('Running all demonstrations...\n');
    _demonstrateAesGcm();
    _demonstrateAesCbc();
    _demonstrateKeyGeneration();
    _demonstrateHmac();
    _demonstrateLoginToken();
    _demonstrateRandomIV();
    _addResult('\n🎉 All demonstrations completed!');
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: const Text('Security Provider Examples'),
        backgroundColor: Theme.of(context).colorScheme.inversePrimary,
      ),
      body: Column(
        children: [
          Padding(
            padding: const EdgeInsets.all(16.0),
            child: Column(
              children: [
                const Text(
                  'Tap any button to see demonstrations',
                  style: TextStyle(fontSize: 16, fontWeight: FontWeight.bold),
                ),
                const SizedBox(height: 16),
                Wrap(
                  spacing: 8,
                  runSpacing: 8,
                  alignment: WrapAlignment.center,
                  children: [
                    ElevatedButton.icon(
                      onPressed: _runAllDemos,
                      icon: const Icon(Icons.play_arrow),
                      label: const Text('Run All'),
                      style: ElevatedButton.styleFrom(
                        backgroundColor: Colors.green,
                        foregroundColor: Colors.white,
                      ),
                    ),
                    ElevatedButton(
                      onPressed: _demonstrateAesGcm,
                      child: const Text('AES-GCM'),
                    ),
                    ElevatedButton(
                      onPressed: _demonstrateAesCbc,
                      child: const Text('AES-CBC'),
                    ),
                    ElevatedButton(
                      onPressed: _demonstrateKeyGeneration,
                      child: const Text('Key Gen'),
                    ),
                    ElevatedButton(
                      onPressed: _demonstrateHmac,
                      child: const Text('HMAC'),
                    ),
                    ElevatedButton(
                      onPressed: _demonstrateLoginToken,
                      child: const Text('Login Token'),
                    ),
                    ElevatedButton(
                      onPressed: _demonstrateRandomIV,
                      child: const Text('Random IV'),
                    ),
                    ElevatedButton.icon(
                      onPressed: _clearResults,
                      icon: const Icon(Icons.clear),
                      label: const Text('Clear'),
                      style: ElevatedButton.styleFrom(
                        backgroundColor: Colors.red,
                        foregroundColor: Colors.white,
                      ),
                    ),
                  ],
                ),
              ],
            ),
          ),
          const Divider(),
          Expanded(
            child: _results.isEmpty
                ? const Center(
                    child: Text(
                      'No results yet.\nTap a button to run a demonstration.',
                      textAlign: TextAlign.center,
                      style: TextStyle(fontSize: 16, color: Colors.grey),
                    ),
                  )
                : ListView.builder(
                    controller: _scrollController,
                    padding: const EdgeInsets.all(16),
                    itemCount: _results.length,
                    itemBuilder: (context, index) {
                      return Padding(
                        padding: const EdgeInsets.only(bottom: 4),
                        child: Text(
                          _results[index],
                          style: const TextStyle(
                            fontFamily: 'monospace',
                            fontSize: 12,
                          ),
                        ),
                      );
                    },
                  ),
          ),
        ],
      ),
    );
  }

  @override
  void dispose() {
    _scrollController.dispose();
    super.dispose();
  }
}
0
likes
150
points
269
downloads

Publisher

unverified uploader

Weekly Downloads

A comprehensive Flutter package for AES encryption (GCM and CBC modes), key generation, and secure data handling with pointycastle.

Repository (GitHub)
View/report issues

Documentation

API reference

License

MIT (license)

Dependencies

crypto, flutter, flutter_models_provider, pointycastle

More

Packages that depend on flutter_security_provider