在Flutter中实现钱包本地加密存储,推荐使用以下方案:
核心依赖包
dependencies:
flutter_secure_storage: ^8.0.0
encrypt: ^5.0.1
shared_preferences: ^2.2.2
实现步骤
1. 创建加密服务类
import 'package:flutter_secure_storage/flutter_secure_storage.dart';
import 'package:encrypt/encrypt.dart';
import 'dart:convert';
class WalletStorageService {
static final FlutterSecureStorage _secureStorage = FlutterSecureStorage();
static final IV _iv = IV.fromLength(16);
// 生成或获取加密密钥
static Future<Key> _getEncryptionKey() async {
String? keyString = await _secureStorage.read(key: 'wallet_encryption_key');
if (keyString == null) {
final key = Key.fromSecureRandom(32);
keyString = base64Url.encode(key.bytes);
await _secureStorage.write(
key: 'wallet_encryption_key',
value: keyString,
);
}
return Key.fromBase64(keyString);
}
// 加密数据
static Future<String> encryptData(String data) async {
final key = await _getEncryptionKey();
final encrypter = Encrypter(AES(key));
final encrypted = encrypter.encrypt(data, iv: _iv);
return encrypted.base64;
}
// 解密数据
static Future<String> decryptData(String encryptedData) async {
try {
final key = await _getEncryptionKey();
final encrypter = Encrypter(AES(key));
final decrypted = encrypter.decrypt64(encryptedData, iv: _iv);
return decrypted;
} catch (e) {
throw Exception('解密失败: $e');
}
}
// 保存钱包数据
static Future<void> saveWalletData(Map<String, dynamic> walletData) async {
final jsonString = jsonEncode(walletData);
final encryptedData = await encryptData(jsonString);
await _secureStorage.write(
key: 'encrypted_wallet_data',
value: encryptedData,
);
}
// 读取钱包数据
static Future<Map<String, dynamic>?> getWalletData() async {
final encryptedData = await _secureStorage.read(key: 'encrypted_wallet_data');
if (encryptedData == null) return null;
try {
final decryptedData = await decryptData(encryptedData);
return jsonDecode(decryptedData);
} catch (e) {
return null;
}
}
// 清除钱包数据
static Future<void> clearWalletData() async {
await _secureStorage.delete(key: 'encrypted_wallet_data');
}
}
2. 使用示例
// 保存钱包信息
void saveWallet() async {
final walletData = {
'privateKey': 'your_private_key_here',
'publicKey': 'your_public_key_here',
'address': 'wallet_address',
'balance': '100.0',
};
await WalletStorageService.saveWalletData(walletData);
}
// 读取钱包信息
void loadWallet() async {
final walletData = await WalletStorageService.getWalletData();
if (walletData != null) {
print('钱包地址: ${walletData['address']}');
print('余额: ${walletData['balance']}');
}
}
安全要点
- 密钥管理:使用FlutterSecureStorage安全存储加密密钥
- AES加密:采用AES对称加密算法保护敏感数据
- 异常处理:妥善处理加解密过程中的异常情况
- 数据验证:读取时验证数据完整性
此方案在iOS上使用Keychain,在Android上使用EncryptedSharedPreferences,确保数据安全存储。