YSAes.dart 1.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051
  1. import 'dart:convert';
  2. import 'package:encrypt/encrypt.dart' as Encrypt;
  3. import 'package:encrypt/encrypt.dart';
  4. import 'package:flutter_wallet/tools/YSTools.dart';
  5. import 'package:hex/hex.dart';
  6. const String _key = '4d7d36f1a720586187281ecbabfcb99f33961897ccd349484e12920c320fcc01';
  7. const String _iv = 'dd25f06a4332857721633b00475ee1a0';
  8. class YSAes{
  9. ///aes加密函数
  10. static String aesEncode3(String content){
  11. LogUtil.d('aesEncode=========$content');
  12. // 将十六进制字符串转换为字节序列
  13. List<int> keyBytes = HEX.decode(_key);
  14. List<int> ivBytes = HEX.decode(_iv);
  15. // 将字节序列转换为 Base64 字符串
  16. String keyBase64 = base64.encode(keyBytes);
  17. String ivBase64 = base64.encode(ivBytes);
  18. // 使用 Base64 字符串创建密钥和 IV
  19. final key = Key.fromBase64(keyBase64);
  20. final iv = IV.fromBase64(ivBase64);
  21. final encrypter = Encrypter(AES(key, mode: AESMode.cbc));
  22. final encrypted = encrypter.encrypt(content, iv: iv);
  23. final decrypted = encrypter.decrypt(encrypted, iv: iv);
  24. print(decrypted); // 显示:Hello, World!
  25. print(encrypted.base64); // 显示加密后的数据
  26. return encrypted.base64;
  27. }
  28. /// 解密函数
  29. static String aesDecrypted(String data){
  30. //加密key
  31. final key = Encrypt.Key.fromUtf8(_key);
  32. //偏移量
  33. final iv = Encrypt.IV.fromUtf8(_iv);
  34. //设置cbc模式
  35. final encrypter = Encrypt.Encrypter(
  36. Encrypt.AES(key, mode: Encrypt.AESMode.cbc, padding: 'PKCS7'));
  37. //解密
  38. LogUtil.d( "解密后的结果:${encrypter.decrypt(Encrypted.fromBase64(data), iv: iv)}");
  39. return encrypter.decrypt(Encrypted.fromBase64(data), iv: iv);
  40. }
  41. }