Flutter加密解密插件flutter_bcrypt的使用
Flutter加密解密插件flutter_bcrypt的使用
简介
flutter_bcrypt
是一个用于Flutter应用程序的bcrypt哈希插件,它委托给Android和iOS的原生实现。Android上的实现使用了patrickfav/bcrypt,而iOS上的实现则使用了felipeflorencio/BCryptSwift。
安装
在pubspec.yaml
文件中添加依赖:
dependencies:
flutter_bcrypt: ^latest_version
确保替换latest_version
为最新版本号。
使用示例
示例代码
以下是一个完整的示例应用,演示如何使用flutter_bcrypt
进行密码哈希和验证:
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:flutter_bcrypt/flutter_bcrypt.dart';
import 'package:dbcrypt/dbcrypt.dart';
void main() => runApp(MyApp());
class MyApp extends StatefulWidget {
@override
_MyAppState createState() => _MyAppState();
}
class _MyAppState extends State<MyApp> {
String _hash = 'Unknown';
String _hash2 = 'TODO';
@override
void initState() {
super.initState();
hash();
}
Future<void> hash() async {
try {
final stopwatch = Stopwatch()..start();
// 哈希密码
stopwatch.reset();
String hash = await FlutterBcrypt.hashPw(
password: r'3282aae5-f104-4639-88a3-3af9a1efb069',
salt: r'$2b$06$C6UzMDM.H6dfI/f/IKxGhu');
print('FlutterBcrypt - hashPw after ${stopwatch.elapsed}');
// 使用DBCrypt库进行哈希对比
stopwatch.reset();
String hash2 = await DBCrypt().hashpw(
r'3282aae5-f104-4639-88a3-3af9a1efb069',
r'$2b$06$C6UzMDM.H6dfI/f/IKxGhu');
print('DBCrypt - hashPw after ${stopwatch.elapsed}');
print("${hash == hash2}"); // should be true
// 生成盐值
stopwatch.reset();
var salt = await FlutterBcrypt.salt();
print('FlutterBcrypt salt ${stopwatch.elapsed} ' + salt);
stopwatch.reset();
var salt2 = DBCrypt().gensalt();
print('DBcrypt salt ${stopwatch.elapsed} ' + salt2);
// 指定轮数生成盐值
stopwatch.reset();
var salt10 = await FlutterBcrypt.saltWithRounds(rounds: 10);
print("FlutterBcrypt salt10 ${stopwatch.elapsed} " + salt10);
stopwatch.reset();
var salt10b = DBCrypt().gensaltWithRounds(10);
print("DBcrypt salt10 ${stopwatch.elapsed} " + salt10b);
// 使用生成的盐值进行哈希
stopwatch.reset();
var pwh = await FlutterBcrypt.hashPw(
password: r'ThisIsSuperSecret', salt: salt);
print("FlutterBcrypt pwh ${stopwatch.elapsed} " + pwh);
stopwatch.reset();
var pwh2 = DBCrypt().hashpw(r'ThisIsSuperSecret', salt2);
print("DBcrypt pwh2 ${stopwatch.elapsed} " + pwh2);
stopwatch.reset();
var pwh10 = await FlutterBcrypt.hashPw(
password: r'ThisIsSuperSecret', salt: salt10);
print("FlutterBcrypt pwh10 ${stopwatch.elapsed} " + pwh10);
stopwatch.reset();
var pwh10b = DBCrypt().hashpw(r'ThisIsSuperSecret', salt10b);
print("DBcrypt pwh10b ${stopwatch.elapsed} " + pwh10b);
// 验证密码
stopwatch.reset();
var result =
await FlutterBcrypt.verify(password: r'ThisIsSuperSecret', hash: pwh2);
print("FlutterBcrypt result: ${stopwatch.elapsed} " + (result ? "ok" : "nok"));
stopwatch.reset();
var result2 = DBCrypt().checkpw(r'ThisIsSuperSecret', pwh2);
print("DBcrypt result: ${stopwatch.elapsed} " + (result2 ? "ok" : "nok"));
stopwatch.reset();
var result10 = await FlutterBcrypt.verify(
password: r'ThisIsSuperSecret', hash: pwh10);
print("FlutterBcrypt result10: ${stopwatch.elapsed} " + (result10 ? "ok" : "nok"));
stopwatch.reset();
var result10b = DBCrypt().checkpw(r'ThisIsSuperSecret', pwh10b);
print("DBCrypt result10: ${stopwatch.elapsed} " + (result10b ? "ok" : "nok"));
// 错误密码验证
stopwatch.reset();
var resultFailed = await FlutterBcrypt.verify(
password: r'ThisPasswordIsWrong', hash: pwh10);
print("FlutterBcrypt resultFailed: ${stopwatch.elapsed} " + (resultFailed ? "nok" : "ok"));
stopwatch.reset();
var resultFailed2 = DBCrypt().checkpw(r'ThisPasswordIsWrong', pwh10b);
print("DBCrypt resultFailed2: ${stopwatch.elapsed} " + (resultFailed2 ? "nok" : "ok"));
} on PlatformException {
_hash = 'Failed to get hash.';
_hash2 = 'Failed to get hash via DBcrypt';
}
if (!mounted) return;
setState(() {
_hash = _hash;
_hash2 = _hash2;
});
}
@override
Widget build(BuildContext context) {
return MaterialApp(
home: Scaffold(
appBar: AppBar(
title: const Text('Bcrypt plugin example app'),
),
body: Center(
child: Text('Hashed password: $_hash, $_hash2\n'),
),
),
);
}
}
关键方法说明
hashPw({required String password, required String salt})
: 使用给定的密码和盐值生成哈希。salt()
: 生成一个随机的盐值。saltWithRounds({int rounds = 10})
: 指定轮数生成盐值,默认为10轮。verify({required String password, required String hash})
: 验证给定的密码是否与哈希匹配。
通过以上步骤,您可以轻松地在Flutter项目中集成并使用flutter_bcrypt
来进行安全的密码哈希和验证操作。
更多关于Flutter加密解密插件flutter_bcrypt的使用的实战系列教程也可以访问 https://www.itying.com/category-92-b0.html
更多关于Flutter加密解密插件flutter_bcrypt的使用的实战系列教程也可以访问 https://www.itying.com/category-92-b0.html
当然,以下是如何在Flutter中使用flutter_bcrypt
插件进行加密和解密的示例代码。flutter_bcrypt
是一个用于在Flutter应用中实现bcrypt加密算法的插件。
首先,确保你已经在pubspec.yaml
文件中添加了flutter_bcrypt
依赖项:
dependencies:
flutter:
sdk: flutter
flutter_bcrypt: ^x.y.z # 请替换为最新版本号
然后,运行flutter pub get
来安装依赖项。
接下来,是一个简单的示例,展示如何使用flutter_bcrypt
进行加密和解密操作。需要注意的是,bcrypt通常用于哈希密码,而不是对称加密和解密。因此,下面的示例将展示如何哈希一个密码并验证它。
import 'package:flutter/material.dart';
import 'package:flutter_bcrypt/flutter_bcrypt.dart';
void main() {
runApp(MyApp());
}
class MyApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
return MaterialApp(
home: Scaffold(
appBar: AppBar(
title: Text('Flutter Bcrypt Example'),
),
body: Center(
child: MyWidget(),
),
),
);
}
}
class MyWidget extends StatefulWidget {
@override
_MyWidgetState createState() => _MyWidgetState();
}
class _MyWidgetState extends State<MyWidget> {
final _passwordController = TextEditingController();
final _hashedPasswordController = TextEditingController();
String? _verificationResult;
void _hashPassword() async {
String? password = _passwordController.text;
if (password != null && password.isNotEmpty) {
String salt = BCrypt.gensaltSync(10); // 生成盐
String hashedPassword = BCrypt.hashpwSync(password, salt);
_hashedPasswordController.text = hashedPassword;
}
}
void _verifyPassword() async {
String? enteredPassword = _passwordController.text;
String? hashedPassword = _hashedPasswordController.text;
if (enteredPassword != null && hashedPassword != null) {
bool result = BCrypt.checkpwSync(enteredPassword, hashedPassword);
setState(() {
_verificationResult = result ? 'Password matches!' : 'Password does not match!';
});
}
}
@override
Widget build(BuildContext context) {
return Column(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
TextField(
controller: _passwordController,
decoration: InputDecoration(labelText: 'Enter Password'),
),
SizedBox(height: 20),
ElevatedButton(
onPressed: _hashPassword,
child: Text('Hash Password'),
),
SizedBox(height: 20),
TextField(
controller: _hashedPasswordController,
decoration: InputDecoration(labelText: 'Hashed Password'),
readOnly: true,
),
SizedBox(height: 20),
ElevatedButton(
onPressed: _verifyPassword,
child: Text('Verify Password'),
),
SizedBox(height: 20),
Text(_verificationResult ?? ''),
],
);
}
}
// 注意:Column 需要在其他布局容器中使用,例如 SingleChildScrollView 和 Padding
// 这里为了简洁直接用了 Column,在实际应用中需要根据情况调整
注意事项:
- 上述代码中的
Column
组件应被包裹在一个能够处理滚动和适当填充的父布局容器中,比如SingleChildScrollView
和Padding
,因为在实际应用中,直接使用Column
可能会导致布局问题。 flutter_bcrypt
插件的BCrypt
类提供的方法都是同步的(Sync
后缀),因此在实际应用中如果涉及到大量数据或复杂操作,可能需要考虑异步处理或性能优化。
这个示例展示了如何使用flutter_bcrypt
插件进行密码哈希和验证,这对于用户密码存储和验证等场景非常有用。