39 lines
1.3 KiB
Dart
39 lines
1.3 KiB
Dart
import 'package:encrypt/encrypt.dart';
|
|
import 'package:pointycastle/asymmetric/api.dart';
|
|
import 'package:dio/dio.dart';
|
|
import '../network/dio_client.dart';
|
|
|
|
class CryptoService {
|
|
static final CryptoService _instance = CryptoService._internal();
|
|
factory CryptoService() => _instance;
|
|
CryptoService._internal();
|
|
|
|
RSAPublicKey? _publicKey;
|
|
|
|
Future<void> fetchPublicKey() async {
|
|
try {
|
|
final dio = Dio(BaseOptions(
|
|
baseUrl: DioClient().dio.options.baseUrl,
|
|
connectTimeout: const Duration(seconds: 10),
|
|
receiveTimeout: const Duration(seconds: 10),
|
|
));
|
|
final response = await dio.get('/auth/public-key');
|
|
final publicKeyBase64 = response.data['publicKey'] as String;
|
|
_publicKey = RSAKeyParser().parse('-----BEGIN PUBLIC KEY-----\n$publicKeyBase64\n-----END PUBLIC KEY-----') as RSAPublicKey;
|
|
} catch (e) {
|
|
throw Exception('Failed to fetch public key: $e');
|
|
}
|
|
}
|
|
|
|
String encrypt(String plainText) {
|
|
if (_publicKey == null) {
|
|
throw Exception('Public key not initialized. Call fetchPublicKey() first.');
|
|
}
|
|
final encrypter = Encrypter(RSA(publicKey: _publicKey));
|
|
final encrypted = encrypter.encrypt(plainText);
|
|
return encrypted.base64;
|
|
}
|
|
|
|
bool get isInitialized => _publicKey != null;
|
|
}
|