import 'dart:convert';
import 'dart:typed_data';

import 'package:encrypt/encrypt.dart';
import 'package:pointycastle/asymmetric/pkcs1.dart';
import 'package:pointycastle/asymmetric/rsa.dart';
import 'package:pointycastle/pointycastle.dart';

import '../values/index.dart';

class RSACryptUtil {

  ///
  ///RSA 加密
  ///
  static Future<String> encodeString(
      String content, String publicKeyStr) async {
        // O2OA后端生成的public Key 没有 PEM 头 所以添加O2.RSA_PEM_KEY_HEADER
    RSAPublicKey publicKey = await _parseKeyFromString(O2.rasPemKeyHeader+publicKeyStr);
    var cipher = PKCS1Encoding(RSAEngine());
    cipher.init(true, PublicKeyParameter<RSAPublicKey>(publicKey));
    Uint8List output = cipher.process(utf8.encode(content) as Uint8List);
    var base64EncodedText = base64Encode(output);
    return base64EncodedText;
  }

  static Future<T> _parseKeyFromString<T extends RSAAsymmetricKey>(
      String publicKeyStr) async {
    final parser = RSAKeyParser();
    return parser.parse(publicKeyStr) as T;
  }
}

// void main() async {
//   debugPrint('开始啦啦啦啦啦。');
//   String key = await RSACryptUtil.encodeString('这里是内容xxxxxxxx',
//       'MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQCWcVZIS57VeOUzi8c01WKvwJK9uRe6hrGTUYmF6J/pI6/UvCbdBWCoErbzsBZOElOH8Sqal3vsNMVLjPYClfoDyYDaUlakP3ldfnXJzAFJVVubF53KadG+fwnh9ZMvxdh7VXVqRL3IQBDwGgzX4rmSK+qkUJjc3OkrNJPB7LLD8QIDAQAB');
//   debugPrint(key);
// }
