Flutter加密解密插件better_cryptography_flutter的使用
Flutter加密解密插件better_cryptography_flutter的使用
概述
这是一个对包better_cryptography
的版本优化,通过使用Android、iOS和Mac OS X的原生API来提升某些加密算法的性能。您必须使用异步方法来获得性能提升。
该库受以下许可协议保护:Apache License 2.0。
在Android中优化的算法
在iOS和Mac OS X中优化的算法
链接
入门指南
在pubspec.yaml
文件中添加依赖项:
dependencies:
better_cryptography: ^2.0.5
better_cryptography_flutter: ^2.0.2
然后使用以下代码启用Flutter加密功能:
import 'package:better_cryptography_flutter/better_cryptography_flutter.dart';
void main() {
// 启用Flutter加密功能
FlutterCryptography.enable();
runApp(const MaterialApp(
title: 'Cryptography demo',
home: CipherPage(),
));
}
有关API的详细信息,请参阅package:better_cryptography的文档。
贡献指南
要测试插件,可以在cryptography_flutter/example/
目录下运行集成测试(查看目录中的README)。
完整示例代码
以下是完整的示例代码,展示如何使用better_cryptography_flutter
插件进行加密和解密操作。
import 'dart:convert';
import 'package:better_cryptography/better_cryptography.dart';
import 'package:better_cryptography_flutter/better_cryptography_flutter.dart';
import 'package:flutter/material.dart';
void main() {
// 启用Flutter加密功能
FlutterCryptography.enable();
runApp(const MaterialApp(
title: 'Cryptography demo',
home: CipherPage(),
));
}
// 将十六进制字符串转换为字节列表
List<int> _fromHex(String s) {
s = s.replaceAll(' ', '').replaceAll('\n', '');
return List<int>.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<int> bytes) {
return bytes.map((e) => e.toRadixString(16).padLeft(2, '0')).join(' ');
}
// 加密页面的状态管理类
class CipherPage extends StatefulWidget {
const CipherPage({Key? key}) : super(key: key);
[@override](/user/override)
State<StatefulWidget> createState() {
return _CipherPageState();
}
}
class _CipherPageState extends State<CipherPage> {
// 定义支持的加密算法
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; // 默认选择AES-GCM (128-bits)
final _secretKeyController = TextEditingController();
final _nonceController = TextEditingController();
List<int> _clearText = []; // 明文数据
final _cipherTextController = TextEditingController(); // 密文数据
final _macController = TextEditingController(); // MAC值
Object? _error;
[@override](/user/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<Cipher>(
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();
},
child: const Text('Generate'),
),
]),
const SizedBox(height: 10),
// 输入随机数
Row(children: [
Expanded(
child: TextField(
controller: _nonceController,
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'),
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),
// 密文输出区域
TextField(
controller: _cipherTextController,
minLines: 1,
maxLines: 16,
enableInteractiveSelection: true,
decoration:
const InputDecoration(labelText: 'Ciphertext (hex)'),
),
const SizedBox(height: 10),
// MAC值输出区域
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<void> _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加密解密插件better_cryptography_flutter的使用的实战系列教程也可以访问 https://www.itying.com/category-92-b0.html
更多关于Flutter加密解密插件better_cryptography_flutter的使用的实战系列教程也可以访问 https://www.itying.com/category-92-b0.html
better_cryptography_flutter
是一个用于 Flutter 应用的加密解密插件,它基于 better_cryptography
库,提供了多种加密算法和工具,方便开发者在 Flutter 应用中进行数据加密和解密操作。
安装
首先,你需要在 pubspec.yaml
文件中添加 better_cryptography_flutter
依赖:
dependencies:
better_cryptography_flutter: ^2.0.0
然后运行 flutter pub get
来安装依赖。
基本用法
1. 导入库
import 'package:better_cryptography_flutter/better_cryptography_flutter.dart';
2. 初始化插件
在使用插件之前,建议先初始化插件:
void main() async {
WidgetsFlutterBinding.ensureInitialized();
await BetterCryptographyFlutter.init();
runApp(MyApp());
}
3. 加密和解密示例
以下是一个使用 AES 加密和解密的示例:
import 'package:better_cryptography/better_cryptography.dart';
void main() async {
WidgetsFlutterBinding.ensureInitialized();
await BetterCryptographyFlutter.init();
// 创建一个 AES 加密器
final algorithm = AesCtr.with256bits(
macAlgorithm: Hmac.sha256(),
);
// 生成一个随机的密钥
final secretKey = await algorithm.newSecretKey();
// 要加密的数据
final plainText = 'Hello, World!';
final secretBox = await algorithm.encrypt(
plainText.codeUnits,
secretKey: secretKey,
);
print('Encrypted: ${secretBox.cipherText}');
// 解密数据
final decrypted = await algorithm.decrypt(
secretBox,
secretKey: secretKey,
);
print('Decrypted: ${String.fromCharCodes(decrypted)}');
}
支持的加密算法
better_cryptography
支持多种加密算法,包括但不限于:
- AES (包括 AES-CBC, AES-CTR, AES-GCM)
- RSA
- HMAC
- SHA (包括 SHA-256, SHA-384, SHA-512)
- ECDSA
- Ed25519
其他功能
- 密钥管理: 可以生成、导入和导出密钥。
- 签名和验证: 支持对数据进行签名和验证。
- 随机数生成: 提供安全的随机数生成器。
示例代码
以下是一个使用 RSA 加密和解密的示例:
import 'package:better_cryptography/better_cryptography.dart';
void main() async {
WidgetsFlutterBinding.ensureInitialized();
await BetterCryptographyFlutter.init();
// 创建一个 RSA 加密器
final algorithm = RsaPss(
sha256(),
keyPair: await RsaKeyPair.newKeyPair(2048),
);
// 要加密的数据
final plainText = 'Hello, World!';
final cipherText = await algorithm.encrypt(
plainText.codeUnits,
);
print('Encrypted: ${cipherText}');
// 解密数据
final decrypted = await algorithm.decrypt(
cipherText,
);
print('Decrypted: ${String.fromCharCodes(decrypted)}');
}