46 lines
1.3 KiB
Dart
46 lines
1.3 KiB
Dart
import 'dart:convert';
|
|
import 'dart:math';
|
|
|
|
import 'package:encrypt/encrypt.dart';
|
|
|
|
import 'api_config.dart';
|
|
|
|
/// AES-128-ECB 加解密
|
|
abstract final class ApiCrypto {
|
|
static final _key = Key.fromUtf8(ApiConfig.aesKey);
|
|
|
|
static final _encrypter = Encrypter(
|
|
AES(
|
|
_key,
|
|
mode: AESMode.ecb,
|
|
padding: 'PKCS7',
|
|
),
|
|
);
|
|
|
|
/// AES 加密,返回 Base64 字符串
|
|
static String encrypt(String plainText) {
|
|
final encrypted = _encrypter.encrypt(plainText);
|
|
return encrypted.base64;
|
|
}
|
|
|
|
/// AES 解密,输入 Base64 字符串
|
|
static String decrypt(String base64Cipher) {
|
|
final encrypted = Encrypted.fromBase64(base64Cipher);
|
|
return _encrypter.decrypt(encrypted);
|
|
}
|
|
|
|
/// 生成随机 Base64 字符串(用于噪音字段)
|
|
/// 使用 Random.secure() 保证密码学安全随机性
|
|
static String randomBase64([int byteLength = 16]) {
|
|
final random = Random.secure();
|
|
final bytes = List<int>.generate(byteLength, (_) => random.nextInt(256));
|
|
return base64Encode(bytes);
|
|
}
|
|
|
|
/// 生成 8 位随机字母数字
|
|
static String randomAlnum() {
|
|
const chars = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789';
|
|
return List.generate(8, (_) => chars[DateTime.now().microsecondsSinceEpoch % chars.length]).join();
|
|
}
|
|
}
|