import 'package:encrypt/encrypt.dart';
import 'package:pointycastle/asymmetric/api.dart';
import 'dart:async';
import 'package:flutter/services.dart' show rootBundle;

/// RSA加密工具
final parser = RSAKeyParser();

class EncryptHelper {
  /// 加密
  ///[src] 待加密字符串
  static Future<String> encode(String src) async {
    String publicKeyString = await rootBundle.loadString('keys/public_key.pem');
    RSAPublicKey publicKey = parser.parse(publicKeyString);
    final encrypter = Encrypter(RSA(publicKey: publicKey));
    return encrypter.encrypt(src).base64;
  }

  /// 解密
  /// [decoded] 待解密字符串
  static Future<String> decode(String decoded) async {
    String privateKeyString =
        await rootBundle.loadString('keys/private_key.pem');

    final privateKey = parser.parse(privateKeyString);

    final encrypter = Encrypter(RSA(privateKey: privateKey));
    return encrypter.decrypt(Encrypted.fromBase64(decoded));
  }
}
