You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Flutter自动登录开发及AES加解密解密失败问题解决

Flutter 自动登录与数据加解密实现

加解密工具类

import 'package:encrypt/encrypt.dart';

class EncryptData {
  static Encrypted? encrypted;
  static var decrypted;
  static final iv = IV.fromLength(16);

  static encryptAES(String plainText, String userKey) {
    print(plainText);
    final key = Key.fromUtf8(userKey);
    final encrypter = Encrypter(AES(key));
    encrypted = encrypter.encrypt(plainText, iv: iv);
    print(encrypted!.base64);
    return encrypted;
  }

  static decryptAES(String encrypted, String userKey, String ivBase64) {
    final key = Key.fromUtf8(userKey);
    final iv = IV.fromBase64(ivBase64); //从ivBase64字符串创建iv
    final encrypter = Encrypter(AES(key));
    decrypted = encrypter.decrypt64(encrypted, iv: iv);
    return decrypted.toString();
  }
}

加密存储逻辑

final storage = FlutterSecureStorage();
SharedPreferences pref = await SharedPreferences.getInstance();
final userId = _auth.currentUser!.uid;
final newDateString = "1kr95ye3mcfgjt124p-54";  
String subUserId = userId.substring(0, 11);  
String key = subUserId + newDateString;
final String ivToBase64 = EncryptData.iv.base64; //将此存储到本地
final String ivFromBase64 = IV.fromBase64(ivToBase64).base64;
var encryptMail;
var encryotPassword;
var encryptMailD;
var encryotPasswordD;
print("ANAHTAR: "+ key);
encryptMail = EncryptData.encryptAES(email.toString(), key);
encryotPassword = EncryptData.encryptAES(sifre.toString(), key); 
encryptMailD = EncryptData.decryptAES(encryptMail.base64, key, ivFromBase64);
encryotPasswordD = EncryptData.decryptAES(encryotPassword.base64, key, ivFromBase64);
print("DENEME : " + email);
print("DENEME : " + sifre);
print("DENEME2 : " + encryptMail.base64);
print("DENEME2 : " + encryotPassword.base64);
print("DENEME3 : " + encryptMailD.toString());
print("DENEME3 : " + encryotPasswordD.toString());
await storage.write(key: 'mail2', value: encryptMail!.base64);
await storage.write(key: 'password2', value: encryotPassword!.base64);
await storage.write(key: 'loginState2', value: true.toString());
await storage.write(key: "ilkOturum", value: "false");
await storage.write(key: "iv2", value: ivToBase64);
pref.setString('mail', encryptMail.base64);
pref.setString('password', encryotPassword.base64);
pref.setString('iv', ivToBase64);
pref.setBool('loginState', true);
print("bilgiler kayıt edildi");

解密读取逻辑

var mail = await storage.read(key: 'mail2');
var password = await storage.read(key: 'password2');
var iv = await storage.read(key: 'iv2');

if (mail != null && password != null) {
  var encryptMailD = EncryptData.decryptAES(mail, key, iv.toString());
  var encryotPasswordD = EncryptData.decryptAES(password, key, iv.toString());
}

此前遇到解密失败问题,目前该功能已正常运行。


内容的提问来源于stack exchange,提问作者bay pilot

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.28 18:10:28