import 'dart:convert';

import 'package:encrypt/encrypt.dart';
import 'package:crypto/crypto.dart';

class CryptoHelper {
  static IV iv = IV.fromLength(16);

  /// 初始化加密
  static Encrypter initEncrypter(String password) {
    final List<int> bytes = utf8.encode(password);
    final Digest md5Bytes = md5.convert(bytes);
    final Key key = Key.fromUtf8(md5Bytes.toString());
    return Encrypter(AES(key, mode: AESMode.ecb));
  }

  /// AES 加密
  static String encryptAes(String plainText, String password) {
    Encrypter encrypter = CryptoHelper.initEncrypter(password);
    return encrypter.encrypt(plainText, iv: iv).base64;
  }

  /// AES 解密
  static String decryptAes(String encrypted, String password) {
    Encrypter encrypter = CryptoHelper.initEncrypter(password);
    return encrypter.decrypt16(encrypted, iv: iv);
  }
}
