### Flutter App Initialization Example Source: https://pub.dev/packages/cryptography_flutter/versions/2.0.0/example A basic Flutter application demonstrating the minimal structure for running a Flutter app. This example sets up the MaterialApp widget and displays a simple 'Example' text on the home screen. It serves as a starting point for integrating other functionalities. ```dart import 'package:flutter/material.dart'; void main() { runApp(MyApp()); } class MyApp extends StatelessWidget { @override Widget build(BuildContext context) { return MaterialApp( title: 'Flutter Demo', theme: ThemeData( primarySwatch: Colors.blue, ), home: Text('Example')); } } ``` -------------------------------- ### Basic Flutter App Setup (Dart) Source: https://pub.dev/packages/cryptography_flutter/versions/2.0.0-nullsafety.0/example This snippet demonstrates a basic Flutter application structure. It includes the necessary imports for Flutter UI components and the main function to run the application. This serves as a starting point for integrating the cryptography_flutter package into a Flutter project. ```dart import 'package:flutter/material.dart'; void main() { runApp(MyApp()); } class MyApp extends StatelessWidget { @override Widget build(BuildContext context) { return MaterialApp( title: 'Flutter Demo', theme: ThemeData( primarySwatch: Colors.blue, ), home: Text('Example')); } } ``` -------------------------------- ### Run End-to-End Flutter Driver Tests (Shell) Source: https://pub.dev/packages/cryptography_flutter/versions/1 Command to run end-to-end (e2e) tests using Flutter driver. This requires navigating to the example directory and specifying the test file path. ```shell cd example flutter driver test/cryptography_flutter_e2e.dart ``` -------------------------------- ### Flutter App Initialization and UI Setup for Cryptography Demo Source: https://pub.dev/packages/cryptography_flutter/versions/2.0.2/example This Dart code initializes the FlutterCryptography plugin and sets up the main UI for a cryptography demonstration application. It defines helper functions for hexadecimal conversions and displays a form for selecting ciphers, inputting keys, and viewing encrypted output. ```dart import 'dart:convert'; import 'package:cryptography/cryptography.dart'; import 'package:cryptography_flutter/cryptography_flutter.dart'; import 'package:flutter/material.dart'; void main() { FlutterCryptography.enable(); runApp(const MaterialApp( title: 'Cryptography demo', home: CipherPage(), )); } List _fromHex(String s) { s = s.replaceAll(' ', '').replaceAll(' ', ''); return List.generate(s.length ~/ 2, (i) { var byteInHex = s.substring(2 * i, 2 * i + 2); if (byteInHex.startsWith('0')) { byteInHex = byteInHex.substring(1); } final result = int.tryParse(byteInHex, radix: 16); if (result == null) { throw StateError('Not valid hexadecimal bytes: $s'); } return result; }); } String _toHex(List bytes) { return bytes.map((e) => e.toRadixString(16).padLeft(2, '0')).join(' '); } class CipherPage extends StatefulWidget { const CipherPage({Key? key}) : super(key: key); @override State createState() { return _CipherPageState(); } } class _CipherPageState extends State { static final _aesCbc128 = AesCbc.with128bits(macAlgorithm: Hmac.sha256()); static final _aesCtr128 = AesCtr.with128bits(macAlgorithm: Hmac.sha256()); static final _aesGcm128 = AesGcm.with128bits(); static final _aesGcm256 = AesGcm.with256bits(); static final _chacha20Poly1305 = Chacha20.poly1305Aead(); static final _xchacha20Poly1305 = Xchacha20.poly1305Aead(); Cipher _cipher = _aesGcm128; final _secretKeyController = TextEditingController(); final _nonceController = TextEditingController(); List _clearText = []; final _cipherTextController = TextEditingController(); final _macController = TextEditingController(); Object? _error; @override Widget build(BuildContext context) { final error = _error; final cipher = _cipher; return Scaffold( body: SafeArea( child: Center( child: Container( constraints: const BoxConstraints(maxWidth: 500), padding: const EdgeInsets.all(20), child: ListView( children: [ InputDecorator( decoration: const InputDecoration(labelText: 'Cipher'), child: DropdownButton( value: _cipher, onChanged: (newValue) { setState(() { _cipher = newValue ?? _aesGcm128; _encrypt(); }); }, items: [ DropdownMenuItem( value: _aesCbc128, child: const Text('AES-CBC (128-bits) + HMAC-SHA256'), ), DropdownMenuItem( value: _aesCtr128, child: const Text('AES-CTR (128-bits) + HMAC-SHA256'), ), DropdownMenuItem( value: _aesGcm128, child: const Text('AES-GCM (128-bits)'), ), DropdownMenuItem( value: _aesGcm256, child: const Text('AES-GCM (256-bits)'), ), DropdownMenuItem( value: _chacha20Poly1305, child: const Text('ChaCha20 + Poly1305'), ), DropdownMenuItem( value: _xchacha20Poly1305, child: const Text('XChaCha20 + Poly1305'), ), ], ), ), const SizedBox(height: 10), Text('Class: ${cipher.runtimeType}'), const SizedBox(height: 10), Row(children: [ Expanded( child: TextField( controller: _secretKeyController, minLines: 1, maxLines: 16, enableInteractiveSelection: true, decoration: InputDecoration( labelText: 'Secret key (${_cipher.secretKeyLength} bytes)')), ), ElevatedButton( onPressed: () async { final secretKey = await _cipher.newSecretKey(); final bytes = await secretKey.extractBytes(); _secretKeyController.text = _toHex(bytes); await _encrypt(); }, ``` -------------------------------- ### Install cryptography_flutter and cryptography Packages Source: https://context7.com/context7/pub_dev_packages_cryptography_flutter/llms.txt This snippet shows how to add the cryptography and cryptography_flutter packages to your Flutter project's pubspec.yaml file. No manual initialization is required for version 2.2.0 and above. ```yaml dependencies: cryptography: ^2.7.0 cryptography_flutter: ^2.3.2 ``` -------------------------------- ### Example pubspec.yaml Dependency for cryptography_flutter Source: https://pub.dev/packages/cryptography_flutter/versions/2.0.0-nullsafety.0/install This snippet shows how the cryptography_flutter dependency is declared in a Flutter project's pubspec.yaml file. It specifies the package name and its version constraint. This is automatically managed by `flutter pub add`. ```yaml dependencies: cryptography_flutter: ^2.0.0-nullsafety.0 ``` -------------------------------- ### Add cryptography_flutter Dependency to Flutter Project Source: https://pub.dev/packages/cryptography_flutter/versions/2.0.0-nullsafety.1/install This command adds the cryptography_flutter package as a dependency to your Flutter project. It automatically updates your pubspec.yaml file and runs `flutter pub get` to download the package. ```bash flutter pub add cryptography_flutter ``` -------------------------------- ### Add cryptography_flutter Dependency with Flutter Source: https://pub.dev/packages/cryptography_flutter/install This snippet shows the command to add the cryptography_flutter package to your Flutter project's dependencies. It automatically updates your pubspec.yaml file and runs 'flutter pub get'. ```bash $ flutter pub add cryptography_flutter ``` -------------------------------- ### Flutter Cipher UI Example Source: https://pub.dev/packages/cryptography_flutter/versions/2.1.0/example Demonstrates a Flutter UI component for performing cryptographic operations using various cipher algorithms provided by the cryptography package. It includes input fields for keys, nonces, and text, along with dropdowns to select different cipher types like AES-CBC, AES-GCM, and ChaCha20-Poly1305. ```dart import 'dart:convert'; import 'package:cryptography/cryptography.dart'; import 'package:cryptography_flutter/cryptography_flutter.dart'; import 'package:flutter/material.dart'; void main() { FlutterCryptography.enable(); runApp(const MaterialApp( title: 'Cryptography demo', home: CipherPage(), )); } // ... _fromHex and _toHex functions ... class CipherPage extends StatefulWidget { const CipherPage({Key? key}) : super(key: key); @override State createState() { return _CipherPageState(); } } class _CipherPageState extends State { static final _aesCbc128 = AesCbc.with128bits(macAlgorithm: Hmac.sha256()); static final _aesCtr128 = AesCtr.with128bits(macAlgorithm: Hmac.sha256()); static final _aesGcm128 = AesGcm.with128bits(); static final _aesGcm256 = AesGcm.with256bits(); static final _chacha20Poly1305 = Chacha20.poly1305Aead(); static final _xchacha20Poly1305 = Xchacha20.poly1305Aead(); Cipher _cipher = _aesGcm128; final _secretKeyController = TextEditingController(); final _nonceController = TextEditingController(); List _clearText = []; final _cipherTextController = TextEditingController(); final _macController = TextEditingController(); Object? _error; @override Widget build(BuildContext context) { final error = _error; final cipher = _cipher; return Scaffold( body: SafeArea( child: Center( child: Container( constraints: const BoxConstraints(maxWidth: 500), padding: const EdgeInsets.all(20), child: ListView( children: [ InputDecorator( decoration: const InputDecoration(labelText: 'Cipher'), child: DropdownButton( value: _cipher, onChanged: (newValue) { setState(() { _cipher = newValue ?? _aesGcm128; _encrypt(); }); }, items: [ DropdownMenuItem( value: _aesCbc128, child: const Text('AES-CBC (128-bits) + HMAC-SHA256'), ), DropdownMenuItem( value: _aesCtr128, child: const Text('AES-CTR (128-bits) + HMAC-SHA256'), ), DropdownMenuItem( value: _aesGcm128, child: const Text('AES-GCM (128-bits)'), ), DropdownMenuItem( value: _aesGcm256, child: const Text('AES-GCM (256-bits)'), ), DropdownMenuItem( value: _chacha20Poly1305, child: const Text('ChaCha20 + Poly1305'), ), DropdownMenuItem( value: _xchacha20Poly1305, child: const Text('XChaCha20 + Poly1305'), ), ], ), ), const SizedBox(height: 10), Text('Class: ${cipher.runtimeType}'), const SizedBox(height: 10), Row(children: [ Expanded( child: TextField( controller: _secretKeyController, onChanged: (value) { _encrypt(); ``` -------------------------------- ### Generate Secret Key and Encrypt Data (Flutter/Dart) Source: https://pub.dev/packages/cryptography_flutter/versions/2.3.0/example This snippet demonstrates how to generate a new secret key, extract its bytes, and use it along with a nonce to encrypt cleartext data. It updates UI controllers with the generated secret key (as hex), ciphertext, and MAC. Includes error handling and state updates. ```dart final secretKey = await _cipher.newSecretKey(); final bytes = await secretKey.extractBytes(); _secretKeyController.text = _toHex(bytes); await _encrypt(); ``` ```dart final cipher = _cipher; final secretBox = await cipher.encrypt( _clearText, secretKey: SecretKeyData( _fromHex(_secretKeyController.text), ), nonce: _fromHex(_nonceController.text), ); _cipherTextController.text = _toHex(secretBox.cipherText); _macController.text = _toHex(secretBox.mac.bytes); setState(() { _error = null; }); ``` -------------------------------- ### Flutter Cryptography Example App - Dart Source: https://pub.dev/packages/cryptography_flutter/example This Dart code demonstrates a Flutter application that utilizes the 'cryptography' package. It allows users to select different cipher algorithms (AES-CBC, AES-CTR, AES-GCM, ChaCha20-Poly1305, XChaCha20-Poly1305) and encrypt/decrypt text. It includes utility functions for hexadecimal conversion and handles user input for secret keys and nonces. ```dart // Copyright 2019-2020 Gohilla. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. import 'dart:convert'; import 'package:cryptography/cryptography.dart'; import 'package:flutter/material.dart'; void main() { runApp(const MaterialApp( title: 'Cryptography demo', home: CipherPage(), )); } List _fromHex(String s) { s = s.replaceAll(' ', '').replaceAll(' ', ''); return List.generate(s.length ~/ 2, (i) { var byteInHex = s.substring(2 * i, 2 * i + 2); if (byteInHex.startsWith('0')) { byteInHex = byteInHex.substring(1); } final result = int.tryParse(byteInHex, radix: 16); if (result == null) { throw StateError('Not valid hexadecimal bytes: $s'); } return result; }); } String _toHex(List bytes) { return bytes.map((e) => e.toRadixString(16).padLeft(2, '0')).join(' '); } class CipherPage extends StatefulWidget { const CipherPage({Key? key}) : super(key: key); @override State createState() { return _CipherPageState(); } } class _CipherPageState extends State { static final _aesCbc128 = AesCbc.with128bits(macAlgorithm: Hmac.sha256()); static final _aesCtr128 = AesCtr.with128bits(macAlgorithm: Hmac.sha256()); static final _aesGcm128 = AesGcm.with128bits(); static final _aesGcm256 = AesGcm.with256bits(); static final _chacha20Poly1305 = Chacha20.poly1305Aead(); static final _xchacha20Poly1305 = Xchacha20.poly1305Aead(); Cipher _cipher = _aesGcm128; final _secretKeyController = TextEditingController(); final _nonceController = TextEditingController(); List _clearText = []; final _cipherTextController = TextEditingController(); final _macController = TextEditingController(); Object? _error; @override Widget build(BuildContext context) { final error = _error; final cipher = _cipher; return Scaffold( body: SafeArea( child: Center( child: Container( constraints: const BoxConstraints(maxWidth: 500), padding: const EdgeInsets.all(20), child: ListView( children: [ InputDecorator( decoration: const InputDecoration(labelText: 'Cipher'), child: DropdownButton( value: _cipher, onChanged: (newValue) { setState(() { _cipher = newValue ?? _aesGcm128; _encrypt(); }); }, items: [ DropdownMenuItem( value: _aesCbc128, child: const Text('AES-CBC (128-bits) + HMAC-SHA256'), ), DropdownMenuItem( value: _aesCtr128, child: const Text('AES-CTR (128-bits) + HMAC-SHA256'), ), DropdownMenuItem( value: _aesGcm128, child: const Text('AES-GCM (128-bits)'), ), DropdownMenuItem( value: _aesGcm256, child: const Text('AES-GCM (256-bits)'), ), DropdownMenuItem( value: _chacha20Poly1305, child: const Text('ChaCha20 + Poly1305'), ), DropdownMenuItem( value: _xchacha20Poly1305, child: const Text('XChaCha20 + Poly1305'), ), ], ), ), const SizedBox(height: 10), Text('Class: ${cipher.runtimeType}'), const SizedBox(height: 10), Row(children: [ Expanded( child: TextField( controller: _secretKeyController, onChanged: (value) { _encrypt(); }, minLines: 1, maxLines: 16, ``` -------------------------------- ### Flutter Cryptography Example UI with AES and ChaCha20 Ciphers Source: https://pub.dev/packages/cryptography_flutter/versions/2.3.1/example This Flutter code demonstrates a UI for cryptographic operations using the 'cryptography' package. It allows users to select different cipher algorithms (AES-CBC, AES-CTR, AES-GCM, ChaCha20, XChaCha20) and inputs for secret keys and nonces. The UI updates to display the ciphertext and MAC, or any errors encountered during encryption. It includes helper functions for hexadecimal conversion. ```dart // Copyright 2019-2020 Gohilla. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. import 'dart:convert'; import 'package:cryptography/cryptography.dart'; import 'package:flutter/material.dart'; void main() { runApp(const MaterialApp( title: 'Cryptography demo', home: CipherPage(), )); } List _fromHex(String s) { s = s.replaceAll(' ', '').replaceAll(' ', ''); return List.generate(s.length ~/ 2, (i) { var byteInHex = s.substring(2 * i, 2 * i + 2); if (byteInHex.startsWith('0')) { byteInHex = byteInHex.substring(1); } final result = int.tryParse(byteInHex, radix: 16); if (result == null) { throw StateError('Not valid hexadecimal bytes: $s'); } return result; }); } String _toHex(List bytes) { return bytes.map((e) => e.toRadixString(16).padLeft(2, '0')).join(' '); } class CipherPage extends StatefulWidget { const CipherPage({Key? key}) : super(key: key); @override State createState() { return _CipherPageState(); } } class _CipherPageState extends State { static final _aesCbc128 = AesCbc.with128bits(macAlgorithm: Hmac.sha256()); static final _aesCtr128 = AesCtr.with128bits(macAlgorithm: Hmac.sha256()); static final _aesGcm128 = AesGcm.with128bits(); static final _aesGcm256 = AesGcm.with256bits(); static final _chacha20Poly1305 = Chacha20.poly1305Aead(); static final _xchacha20Poly1305 = Xchacha20.poly1305Aead(); Cipher _cipher = _aesGcm128; final _secretKeyController = TextEditingController(); final _nonceController = TextEditingController(); List _clearText = []; final _cipherTextController = TextEditingController(); final _macController = TextEditingController(); Object? _error; @override Widget build(BuildContext context) { final error = _error; final cipher = _cipher; return Scaffold( body: SafeArea( child: Center( child: Container( constraints: const BoxConstraints(maxWidth: 500), padding: const EdgeInsets.all(20), child: ListView( children: [ InputDecorator( decoration: const InputDecoration(labelText: 'Cipher'), child: DropdownButton( value: _cipher, onChanged: (newValue) { setState(() { _cipher = newValue ?? _aesGcm128; _encrypt(); }); }, items: [ DropdownMenuItem( value: _aesCbc128, child: const Text('AES-CBC (128-bits) + HMAC-SHA256'), ), DropdownMenuItem( value: _aesCtr128, child: const Text('AES-CTR (128-bits) + HMAC-SHA256'), ), DropdownMenuItem( value: _aesGcm128, child: const Text('AES-GCM (128-bits)'), ), DropdownMenuItem( value: _aesGcm256, child: const Text('AES-GCM (256-bits)'), ), DropdownMenuItem( value: _chacha20Poly1305, child: const Text('ChaCha20 + Poly1305'), ), DropdownMenuItem( value: _xchacha20Poly1305, child: const Text('XChaCha20 + Poly1305'), ), ], ), ), const SizedBox(height: 10), Text('Class: ${cipher.runtimeType}'), const SizedBox(height: 10), Row(children: [ Expanded( child: TextField( controller: _secretKeyController, onChanged: (value) { _encrypt(); }, minLines: 1, maxLines: 16, ), ) ]), const SizedBox(height: 10), TextField( controller: _nonceController, decoration: const InputDecoration(labelText: 'Nonce (hex)'), onChanged: (value) { _encrypt(); }, minLines: 1, maxLines: 16, ), const SizedBox(height: 10), TextField( controller: _cipherTextController, decoration: const InputDecoration(labelText: 'Ciphertext (hex)'), readOnly: true, ), const SizedBox(height: 10), TextField( controller: _macController, decoration: const InputDecoration(labelText: 'MAC (hex)'), readOnly: true, ), if (error != null) ...[ const SizedBox(height: 10), Text('Error: $error'), ] ], ), ), ), ), ); } Future _encrypt() async { try { final secretKey = _fromHex(_secretKeyController.text); final nonce = _fromHex(_nonceController.text); final plainText = _clearText; final signature = await _cipher.encrypt(plainText, secretKey: SecretKey(secretKey), nonce: Nonce(nonce)); setState(() { _cipherTextController.text = _toHex(signature.bytes); _macController.text = signature.mac == null ? '' : _toHex(signature.mac!.bytes); _error = null; }); } catch (e) { setState(() { _cipherTextController.clear(); _macController.clear(); _error = e; }); } } } ``` -------------------------------- ### Flutter ChaCha20-Poly1305 AEAD Encryption with Platform Acceleration Source: https://context7.com/context7/pub_dev_packages_cryptography_flutter/llms.txt Illustrates ChaCha20-Poly1305 authenticated encryption. The cryptography_flutter plugin leverages platform acceleration for ChaCha20-Poly1305 on Android and Apple platforms, providing significant speed improvements. This example covers creating a secret key, nonce, encrypting data with Additional Authenticated Data (AAD), and decrypting/verifying the ciphertext. ```dart import 'dart:convert'; import 'package:cryptography/cryptography.dart'; Future encryptWithChacha20() async { // FlutterChacha20 is used on Android and Apple platforms (up to 50x faster) // BackgroundChacha20 is used on Windows/Linux final algorithm = Chacha20.poly1305Aead(); // Create secret key from hex string final secretKeyData = SecretKeyData( List.generate(32, (i) => i * 7 % 256), // Example key ); // Create nonce (12 bytes for ChaCha20-Poly1305) final nonce = List.generate(12, (i) => i * 3 % 256); // Encrypt with additional authenticated data (AAD) final plaintext = utf8.encode('Top secret message'); final aad = utf8.encode('authenticated-header'); final secretBox = await algorithm.encrypt( plaintext, secretKey: secretKeyData, nonce: nonce, aad: aad, ); print('Ciphertext length: ${secretBox.cipherText.length}'); print('MAC: ${secretBox.mac.bytes.map((e) => e.toRadixString(16).padLeft(2, '0')).join()}'); // Decrypt and verify AAD try { final decrypted = await algorithm.decrypt( secretBox, secretKey: secretKeyData, aad: aad, ); print('Decrypted: ${utf8.decode(decrypted)}'); } catch (e) { print('Authentication failed: $e'); } } ``` -------------------------------- ### Encrypt with AES-CTR and HMAC in Dart Source: https://context7.com/context7/pub_dev_packages_cryptography_flutter/llms.txt Illustrates stream encryption using AES-CTR mode with HMAC-SHA512 authentication. This example shows creating a secret key and nonce, encrypting streaming data, and then decrypting it. AES-CTR is efficient for encrypting large amounts of data or streams. ```dart import 'dart:convert'; import 'package:cryptography/cryptography.dart'; Future encryptWithAesCtr() async { // BackgroundAesCtr used for large inputs final algorithm = AesCtr.with256bits(macAlgorithm: Hmac.sha512()); // Create secret key from bytes final secretKeyBytes = List.generate(32, (i) => (i * 13) % 256); final secretKey = SecretKeyData(secretKeyBytes); // Create nonce (counter initialization) final nonce = List.generate(16, (i) => (i * 7) % 256); // Encrypt streaming data final plaintext = utf8.encode('Large file data chunk that can be processed as a stream'); final secretBox = await algorithm.encrypt( plaintext, secretKey: secretKey, nonce: nonce, ); print('Original length: ${plaintext.length}'); print('Ciphertext length: ${secretBox.cipherText.length}'); print('HMAC-SHA512: ${secretBox.mac.bytes.map((e) => e.toRadixString(16).padLeft(2, '0')).join()}'); // Decrypt final decrypted = await algorithm.decrypt( secretBox, secretKey: secretKey, ); print('Stream decryption successful: ${plaintext.length == decrypted.length}'); } ``` -------------------------------- ### Basic Flutter Main Function Source: https://pub.dev/packages/cryptography_flutter/versions/1.0.0/example This is a basic entry point for a Flutter application. It initializes the application and typically contains the root widget. The '...' placeholder indicates where the main application logic and UI would be defined. No external dependencies are explicitly shown in this snippet. ```dart void main() { // ... } ``` -------------------------------- ### Run Flutter Tests (Shell) Source: https://pub.dev/packages/cryptography_flutter/versions/1 Command to execute tests for the 'no plugin available' scenario within the project. This is useful for verifying the core functionality of the package without involving platform-specific plugins. ```shell flutter test ``` -------------------------------- ### Enable Flutter Cryptography and Run Demo App Source: https://pub.dev/packages/cryptography_flutter/versions/2.1.1/example This Flutter code snippet demonstrates how to enable the Flutter cryptography plugin and run a sample application that showcases different cryptographic ciphers. It includes helper functions for hexadecimal conversion and a UI for selecting and testing ciphers. ```dart import 'dart:convert'; import 'package:cryptography/cryptography.dart'; import 'package:cryptography_flutter/cryptography_flutter.dart'; import 'package:flutter/material.dart'; void main() { // Enable Flutter cryptography FlutterCryptography.enable(); runApp(const MaterialApp( title: 'Cryptography demo', home: CipherPage(), )); } List _fromHex(String s) { s = s.replaceAll(' ', '').replaceAll('\n', ''); return List.generate(s.length ~/ 2, (i) { var byteInHex = s.substring(2 * i, 2 * i + 2); if (byteInHex.startsWith('0')) { byteInHex = byteInHex.substring(1); } final result = int.tryParse(byteInHex, radix: 16); if (result == null) { throw StateError('Not valid hexadecimal bytes: $s'); } return result; }); } String _toHex(List bytes) { return bytes.map((e) => e.toRadixString(16).padLeft(2, '0')).join(' '); } class CipherPage extends StatefulWidget { const CipherPage({Key? key}) : super(key: key); @override State createState() { return _CipherPageState(); } } class _CipherPageState extends State { static final _aesCbc128 = AesCbc.with128bits(macAlgorithm: Hmac.sha256()); static final _aesCtr128 = AesCtr.with128bits(macAlgorithm: Hmac.sha256()); static final _aesGcm128 = AesGcm.with128bits(); static final _aesGcm256 = AesGcm.with256bits(); static final _chacha20Poly1305 = Chacha20.poly1305Aead(); static final _xchacha20Poly1305 = Xchacha20.poly1305Aead(); Cipher _cipher = _aesGcm128; final _secretKeyController = TextEditingController(); final _nonceController = TextEditingController(); List _clearText = []; final _cipherTextController = TextEditingController(); final _macController = TextEditingController(); Object? _error; @override Widget build(BuildContext context) { final error = _error; final cipher = _cipher; return Scaffold( body: SafeArea( child: Center( child: Container( constraints: const BoxConstraints(maxWidth: 500), padding: const EdgeInsets.all(20), child: ListView( children: [ InputDecorator( decoration: const InputDecoration(labelText: 'Cipher'), child: DropdownButton( value: _cipher, onChanged: (newValue) { setState(() { _cipher = newValue ?? _aesGcm128; _encrypt(); }); }, items: [ DropdownMenuItem( value: _aesCbc128, child: const Text('AES-CBC (128-bits) + HMAC-SHA256'), ), DropdownMenuItem( value: _aesCtr128, child: const Text('AES-CTR (128-bits) + HMAC-SHA256'), ), DropdownMenuItem( value: _aesGcm128, child: const Text('AES-GCM (128-bits)'), ), DropdownMenuItem( value: _aesGcm256, child: const Text('AES-GCM (256-bits)'), ), DropdownMenuItem( value: _chacha20Poly1305, child: const Text('ChaCha20 + Poly1305'), ), DropdownMenuItem( value: _xchacha20Poly1305, child: const Text('XChaCha20 + Poly1305'), ), ], ), ), const SizedBox(height: 10), Text('Class: ${cipher.runtimeType}'), const SizedBox(height: 10), Row(children: [ Expanded( child: TextField( controller: _secretKeyController, onChanged: (value) { _encrypt(); ``` -------------------------------- ### Enable Flutter Cryptography Source: https://pub.dev/packages/cryptography_flutter/versions/2.1.0/example Initializes and enables the platform-specific cryptographic APIs for use within a Flutter application. This is a prerequisite for utilizing the performance benefits offered by the cryptography_flutter package. ```dart import 'package:cryptography_flutter/cryptography_flutter.dart'; void main() { // Enable Flutter cryptography FlutterCryptography.enable(); runApp(const MaterialApp( title: 'Cryptography demo', home: CipherPage(), )); } ``` -------------------------------- ### Flutter Encryption UI and Logic Source: https://pub.dev/packages/cryptography_flutter/versions/2.1.0/example This snippet implements the user interface and core logic for encryption using the 'cryptography_flutter' package. It includes input fields for secret keys, nonces, cleartext, and output fields for ciphertext and MAC. It relies on helper functions like _toHex and _fromHex for byte conversions and the 'cryptography' package for encryption operations. ```dart import 'dart:convert'; // ... (previous code for UI elements like InputDecoration, ElevatedButton, etc.) class _MyHomePageState extends State { // ... (other state variables like _cipher, _secretKeyController, etc.) String? _error; final List _clearText = []; final _cipherTextController = TextEditingController(); final _macController = TextEditingController(); @override void initState() { super.initState(); // Initialize controllers and cipher } @override void dispose() { _secretKeyController.dispose(); _nonceController.dispose(); _cipherTextController.dispose(); _macController.dispose(); super.dispose(); } // Helper function to convert bytes to hex string String _toHex(List bytes) { return bytes.map((byte) => byte.toRadixString(16).padLeft(2, '0')).join(); } // Helper function to convert hex string to bytes List _fromHex(String hex) { final bytes = []; for (int i = 0; i < hex.length; i += 2) { bytes.add(int.parse(hex.substring(i, i + 2), radix: 16)); } return bytes; } @override Widget build(BuildContext context) { return Scaffold( appBar: AppBar(title: const Text('Cryptography Example')), body: Padding( padding: const EdgeInsets.all(16.0), child: SingleChildScrollView( child: Column( crossAxisAlignment: CrossAxisAlignment.start, children: [ // Secret Key Input Row(children: [ Expanded( child: TextField( controller: _secretKeyController, onChanged: (value) { _encrypt(); }, minLines: 1, maxLines: 16, enableInteractiveSelection: true, decoration: InputDecoration( labelText: 'Secret key (${_cipher.secretKeyLength} bytes)') ), ), ElevatedButton( onPressed: () async { final secretKey = await _cipher.newSecretKey(); final bytes = await secretKey.extractBytes(); _secretKeyController.text = _toHex(bytes); await _encrypt(); }, child: const Text('Generate'), ), ]), const SizedBox(height: 10), // Nonce Input Row(children: [ Expanded( child: TextField( controller: _nonceController, onChanged: (value) { _encrypt(); }, minLines: 1, maxLines: 16, enableInteractiveSelection: true, decoration: InputDecoration( labelText: 'Nonce (${_cipher.nonceLength} bytes)') ), ), ElevatedButton( onPressed: () async { _nonceController.text = _toHex(_cipher.newNonce()); await _encrypt(); }, child: const Text('Generate'), ), ]), const SizedBox(height: 30), const Text('Encrypt'), // Cleartext Input TextField( onChanged: (newValue) { try { _clearText = utf8.encode(newValue); _encrypt(); } catch (error) { setState(() { _error = error; }); } }, minLines: 1, maxLines: 16, enableInteractiveSelection: true, decoration: const InputDecoration(labelText: 'Cleartext (text)') ), const SizedBox(height: 10), // Ciphertext Output TextField( controller: _cipherTextController, minLines: 1, maxLines: 16, enableInteractiveSelection: true, decoration: const InputDecoration(labelText: 'Ciphertext (hex)') ), const SizedBox(height: 10), // MAC Output TextField( controller: _macController, minLines: 1, maxLines: 16, enableInteractiveSelection: true, decoration: const InputDecoration( labelText: 'Message Authentication Code (MAC)') ), const SizedBox(height: 10), if (_error != null) Text(_error.toString()), ], ), ), ), ); } Future _encrypt() async { try { final cipher = _cipher; final secretBox = await cipher.encrypt( _clearText, secretKey: SecretKeyData( _fromHex(_secretKeyController.text), ), nonce: _fromHex(_nonceController.text), ); _cipherTextController.text = _toHex(secretBox.cipherText); _macController.text = _toHex(secretBox.mac.bytes); setState(() { _error = null; }); } catch (error, stackTrace) { setState(() { _error = '$error\n\n$stackTrace'; _cipherTextController.text = ''; _macController.text = ''; }); return; } } } ``` -------------------------------- ### Generate Secret Key and Encrypt Data (Dart) Source: https://pub.dev/packages/cryptography_flutter/example This snippet demonstrates generating a new secret key, extracting its bytes, and initiating an encryption process using the cryptography_flutter package. It also handles updating the UI with the generated key and encrypted data. Dependencies include 'package:cryptography'. ```dart final secretKey = await _cipher.newSecretKey(); final bytes = await secretKey.extractBytes(); _secretKeyController.text = _toHex(bytes); await _encrypt(); ``` -------------------------------- ### Encrypt Data with Flutter Cryptography Source: https://pub.dev/packages/cryptography_flutter/versions/2.0.2/example Demonstrates the encryption process using the cryptography_flutter package. It takes cleartext, a secret key, and a nonce as input, and outputs ciphertext and a Message Authentication Code (MAC). Error handling is included for invalid inputs or encryption failures. Dependencies include 'cryptography' and 'flutter'. ```dart import 'dart:convert'; // Assuming _cipher, _clearText, _secretKeyController, _nonceController, _cipherTextController, _macController, and setState are defined elsewhere in the class. Future _encrypt() async { setState(() { _error = null; }); try { final cipher = _cipher; final secretBox = await cipher.encrypt( _clearText, secretKey: SecretKeyData( _fromHex(_secretKeyController.text), ), nonce: _fromHex(_nonceController.text), ); _cipherTextController.text = _toHex(secretBox.cipherText); _macController.text = _toHex(secretBox.mac.bytes); } catch (error) { setState(() { _error = error; _cipherTextController.text = ''; _macController.text = ''; }); return; } } ``` -------------------------------- ### Flutter Cryptography Demo UI Source: https://pub.dev/packages/cryptography_flutter/versions/2.2.0/example A Flutter application demonstrating the usage of the 'cryptography' package with various cipher algorithms. It allows users to input secret keys and nonces, encrypt and decrypt data, and observe the resulting ciphertext and MAC. Error handling is included for invalid inputs. ```dart // Copyright 2019-2020 Gohilla. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. import 'dart:convert'; import 'package:cryptography/cryptography.dart'; import 'package:flutter/material.dart'; void main() { runApp(const MaterialApp( title: 'Cryptography demo', home: CipherPage(), )); } List _fromHex(String s) { s = s.replaceAll(' ', '').replaceAll('\n', ''); return List.generate(s.length ~/ 2, (i) { var byteInHex = s.substring(2 * i, 2 * i + 2); if (byteInHex.startsWith('0')) { byteInHex = byteInHex.substring(1); } final result = int.tryParse(byteInHex, radix: 16); if (result == null) { throw StateError('Not valid hexadecimal bytes: $s'); } return result; }); } String _toHex(List bytes) { return bytes.map((e) => e.toRadixString(16).padLeft(2, '0')).join(' '); } class CipherPage extends StatefulWidget { const CipherPage({Key? key}) : super(key: key); @override State createState() { return _CipherPageState(); } } class _CipherPageState extends State { static final _aesCbc128 = AesCbc.with128bits(macAlgorithm: Hmac.sha256()); static final _aesCtr128 = AesCtr.with128bits(macAlgorithm: Hmac.sha256()); static final _aesGcm128 = AesGcm.with128bits(); static final _aesGcm256 = AesGcm.with256bits(); static final _chacha20Poly1305 = Chacha20.poly1305Aead(); static final _xchacha20Poly1305 = Xchacha20.poly1305Aead(); Cipher _cipher = _aesGcm128; final _secretKeyController = TextEditingController(); final _nonceController = TextEditingController(); List _clearText = []; final _cipherTextController = TextEditingController(); final _macController = TextEditingController(); Object? _error; @override Widget build(BuildContext context) { final error = _error; final cipher = _cipher; return Scaffold( body: SafeArea( child: Center( child: Container( constraints: const BoxConstraints(maxWidth: 500), padding: const EdgeInsets.all(20), child: ListView( children: [ InputDecorator( decoration: const InputDecoration(labelText: 'Cipher'), child: DropdownButton( value: _cipher, onChanged: (newValue) { setState(() { _cipher = newValue ?? _aesGcm128; _encrypt(); }); }, items: [ DropdownMenuItem( value: _aesCbc128, child: const Text('AES-CBC (128-bits) + HMAC-SHA256'), ), DropdownMenuItem( value: _aesCtr128, child: const Text('AES-CTR (128-bits) + HMAC-SHA256'), ), DropdownMenuItem( value: _aesGcm128, child: const Text('AES-GCM (128-bits)'), ), DropdownMenuItem( value: _aesGcm256, child: const Text('AES-GCM (256-bits)'), ), DropdownMenuItem( value: _chacha20Poly1305, child: const Text('ChaCha20 + Poly1305'), ), DropdownMenuItem( value: _xchacha20Poly1305, child: const Text('XChaCha20 + Poly1305'), ), ], ), ), const SizedBox(height: 10), Text('Class: ${cipher.runtimeType}'), const SizedBox(height: 10), Row(children: [ Expanded( child: TextField( controller: _secretKeyController, onChanged: (value) { _encrypt(); }, minLines: 1, maxLines: 16, ), ) ]) ] ) ) ) ) ); } void _encrypt() { setState(() { _error = null; _cipherTextController.text = ''; _macController.text = ''; try { final secretKey = _secretKeyController.text; final nonce = _nonceController.text; if (secretKey.isEmpty) { return; } final bytes = utf8.encode(secretKey); if (bytes.isEmpty) { return; } final key = SecretKey(bytes); final nonceList = nonce.isEmpty ? null : _fromHex(nonce); _cipher.encrypt(key, bytes, nonce: nonceList).then((value) { setState(() { _clearText = bytes; _cipherTextController.text = _toHex(value.cipherText.bytes); _macController.text = _toHex(value.mac.bytes); }); }).catchError((e) { _error = e; }); } catch (e) { _error = e; } }); } } ```