Flutter本地认证加密插件local_auth_crypto的使用
Flutter本地认证加密插件local_auth_crypto的使用
local_auth_crypto
在Android和iOS设备上通过生物识别允许本地认证+加密。
特性
新实例
final localAuthCrypto = LocalAuthCrypto.instance;
加密
await localAuthCrypto.encrypt(message);
PromptInfo
BiometricPromptInfo(
title: 'BIOMETRIC',
subtitle: 'Please scan biometric to decrypt',
negativeButton: 'CANCEL',
);
解密
await localAuthCrypto.authenticate(promptInfo, cipherText);
开始使用
使用非常简单!你需要确保在你的Flutter项目中添加local_auth_crypto
作为依赖项。
local_auth_crypto: "^1.1.1"
使用方法
Flutter
加密
final localAuthCrypto = localAuthCrypto.instance;
final message = 'TOKEN';
final cipherText = await localAuthCrypto.encrypt(message);
解密
final localAuthCrypto = localAuthCrypto.instance;
final promptInfo = BiometricPromptInfo(
title: 'BIOMETRIC',
subtitle: 'Please scan biometric to decrypt',
negativeButton: 'CANCEL',
);
final plainText = await localAuthCrypto.authenticate(promptInfo, cipherText);
Android
更新代码在 MainActivity.kt
文件中
import io.flutter.embedding.android.FlutterFragmentActivity
class MainActivity : FlutterFragmentActivity()
在 AndroidManifest.xml
文件中添加权限
<uses-permission android:name="android.permission.USE_BIOMETRIC" />
iOS
在 info.plist
文件中添加隐私描述
<dict>
<key>NSFaceIDUsageDescription</key>
<string>This application wants to access your TouchID or FaceID</string>
</dict>
完整示例
以下是一个完整的示例,展示了如何使用local_auth_crypto
进行加密和解密操作。
import 'package:flutter/material.dart';
import 'package:local_auth_crypto/local_auth_crypto.dart';
void main() {
runApp(const MyApp());
}
class MyApp extends StatefulWidget {
const MyApp({super.key});
[@override](/user/override)
State<MyApp> createState() => _MyAppState();
}
class _MyAppState extends State<MyApp> {
final String _biometricToken = 'TOKEN FROM SERVER';
String? _biometricTokenCipherText = '';
String? _biometricTokenPlainText = '';
final _localAuthCrypto = LocalAuthCrypto.instance;
[@override](/user/override)
void initState() {
super.initState();
_processEncrypt();
_processCanEvaluatePolicy();
}
[@override](/user/override)
Widget build(BuildContext context) {
return MaterialApp(
home: Scaffold(
appBar: AppBar(
title: const Text('LOCAL AUTH PLUS'),
),
body: SafeArea(
child: SingleChildScrollView(
child: Container(
margin: const EdgeInsets.all(16),
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Text(
'TOKEN',
style: Theme.of(context).textTheme.titleLarge,
),
const SizedBox(height: 8),
CardBox(content: _biometricToken),
const SizedBox(height: 16),
Text(
'CIPHER TEXT',
style: Theme.of(context).textTheme.titleLarge,
),
const SizedBox(height: 8),
CardBox(content: _biometricTokenCipherText ?? ''),
const SizedBox(height: 16),
Text(
'PLAIN TEXT',
style: Theme.of(context).textTheme.titleLarge,
),
const SizedBox(height: 8),
CardBox(content: _biometricTokenPlainText ?? ''),
const SizedBox(height: 46),
SizedBox(
width: double.infinity,
child: Column(
crossAxisAlignment: CrossAxisAlignment.center,
children: [
IconButton(
onPressed: () {
_processDecrypt();
},
icon: const Icon(Icons.fingerprint_outlined),
iconSize: 80,
),
const Text('Decrypt by Biometric'),
],
),
),
],
),
),
),
),
),
);
}
void _processEncrypt() async {
_biometricTokenCipherText = await _localAuthCrypto.encrypt(_biometricToken);
setState(() {});
}
void _processDecrypt() async {
final promptInfo = BiometricPromptInfo(
title: 'BIOMETRIC',
subtitle: 'Please scan biometric to decrypt',
negativeButton: 'CANCEL',
);
_biometricTokenPlainText = await _localAuthCrypto.authenticate(
promptInfo,
_biometricTokenCipherText ?? '',
);
setState(() {});
}
void _processCanEvaluatePolicy() async {
final status = await _localAuthCrypto
.evaluatePolicy('Allow biometric to authenticate');
print('status: $status');
}
}
class CardBox extends StatelessWidget {
final String content;
const CardBox({Key? key, required this.content}) : super(key: key);
[@override](/user/override)
Widget build(BuildContext context) {
return Container(
width: double.infinity,
decoration: BoxDecoration(
color: Colors.grey.shade300,
borderRadius: BorderRadius.circular(16),
),
child: Padding(
padding: const EdgeInsets.all(16.0),
child: Text(content),
),
);
}
}
更多关于Flutter本地认证加密插件local_auth_crypto的使用的实战系列教程也可以访问 https://www.itying.com/category-92-b0.html
1 回复
更多关于Flutter本地认证加密插件local_auth_crypto的使用的实战系列教程也可以访问 https://www.itying.com/category-92-b0.html
当然,以下是如何在Flutter项目中使用local_auth_crypto
插件来实现本地认证加密的一个代码示例。这个插件结合了设备的生物认证(如指纹或面部识别)与数据加密功能,确保用户数据的安全性。
首先,确保你已经在pubspec.yaml
文件中添加了local_auth_crypto
依赖:
dependencies:
flutter:
sdk: flutter
local_auth_crypto: ^x.y.z # 请替换为最新版本号
然后运行flutter pub get
来安装依赖。
接下来是代码示例,展示如何使用local_auth_crypto
插件:
import 'package:flutter/material.dart';
import 'package:local_auth_crypto/local_auth_crypto.dart';
import 'dart:convert';
void main() {
runApp(MyApp());
}
class MyApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
return MaterialApp(
home: Scaffold(
appBar: AppBar(
title: Text('Local Auth Crypto Demo'),
),
body: Center(
child: LocalAuthCryptoDemo(),
),
),
);
}
}
class LocalAuthCryptoDemo extends StatefulWidget {
@override
_LocalAuthCryptoDemoState createState() => _LocalAuthCryptoDemoState();
}
class _LocalAuthCryptoDemoState extends State<LocalAuthCryptoDemo> {
final LocalAuthCrypto _localAuthCrypto = LocalAuthCrypto();
String? _encryptedData;
String? _decryptedData;
@override
Widget build(BuildContext context) {
return Column(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
ElevatedButton(
onPressed: _encryptData,
child: Text('Encrypt Data'),
),
SizedBox(height: 20),
ElevatedButton(
onPressed: _decryptData,
child: Text('Decrypt Data'),
enabled: _encryptedData != null,
),
SizedBox(height: 20),
Text('Encrypted Data: $_encryptedData'),
SizedBox(height: 20),
Text('Decrypted Data: $_decryptedData'),
],
);
}
Future<void> _encryptData() async {
bool authenticated = await _localAuthCrypto.authenticateWithBiometrics(
localizedReason: 'Please authenticate to encrypt data',
stickyAuth: true,
);
if (authenticated) {
String plainText = 'This is a secret message!';
String encrypted = await _localAuthCrypto.encrypt(plainText);
setState(() {
_encryptedData = encrypted;
_decryptedData = null;
});
} else {
ScaffoldMessenger.of(context).showSnackBar(
SnackBar(content: Text('Authentication failed')),
);
}
}
Future<void> _decryptData() async {
bool authenticated = await _localAuthCrypto.authenticateWithBiometrics(
localizedReason: 'Please authenticate to decrypt data',
stickyAuth: false,
);
if (authenticated && _encryptedData != null) {
String decrypted = await _localAuthCrypto.decrypt(_encryptedData!);
setState(() {
_decryptedData = decrypted;
});
} else {
ScaffoldMessenger.of(context).showSnackBar(
SnackBar(content: Text('Authentication failed or no encrypted data')),
);
}
}
}
代码说明:
- 依赖引入:在
pubspec.yaml
中添加local_auth_crypto
依赖。 - UI布局:使用Flutter的
Material
组件创建一个简单的UI,包含两个按钮用于加密和解密数据,以及两个Text
组件用于显示加密和解密后的数据。 - 加密数据:点击“Encrypt Data”按钮时,会首先触发生物认证(如指纹或面部识别)。认证成功后,将明文数据加密并显示在UI上。
- 解密数据:点击“Decrypt Data”按钮时,同样会触发生物认证。认证成功后,将之前加密的数据解密并显示在UI上。
注意事项:
- 在实际使用中,请确保遵循最佳实践,如安全地存储密钥和加密数据。
stickyAuth
参数决定了认证是否在一次成功后保持有效,直到应用重启。根据需求调整此参数。- 生物认证失败时,应妥善处理用户反馈,避免多次失败导致用户体验下降。
这个示例提供了一个基础框架,你可以根据具体需求进行扩展和定制。