
import 'package:cashier_reserve/common/print/print.dart';
import 'package:encrypt/encrypt.dart';
import 'package:pointycastle/asymmetric/api.dart';

class PwdEncrypt {
  static const _rsaPubKey =
      "MFwwDQYJKoZIhvcNAQEBBQADSwAwSAJBANL378k3RiZHWx5AfJqdH9xRNBmD9wGD2iRe41HdTNF8RUhNnHit5NpMNtGL0NPTSSpPjjI1kJfVorRvaQerUgkCAwEAAQ==";

  static String encrypt(String pwd) {
    return _encryptString(publicKeyString: _rsaPubKey, plainText: pwd);
  }

  /// 利用公钥进行加密
  static String _encryptString(
      {required String publicKeyString, required String plainText}) {
    String key = '-----BEGIN PUBLIC KEY-----\n\r';
    int length = 0;
    const baseLen = 64;
    while (length < publicKeyString.length) {
      bool over = length + baseLen > publicKeyString.length;
      key += publicKeyString.substring(
          length, over ? publicKeyString.length : length + baseLen);
      key += '\n\r';
      length += baseLen;
    }
    key += '-----END PUBLIC KEY-----';

    yjPrint(key);

    final publicKey = _parsePublicKeyFromPem(key);

    final encrypt = Encrypter(RSA(publicKey: publicKey));

    final encryptedText = encrypt.encrypt(plainText);

    return encryptedText.base64;
  }

  /// 通过PEM字符串解析公钥字符串
  static RSAPublicKey _parsePublicKeyFromPem(String pemString) {
    final key = RSAKeyParser().parse(pemString);
    return key as RSAPublicKey;
  }
}
