rsa_crypt_util.dart 1.4 KB

123456789101112131415161718192021222324252627282930313233343536373839
  1. import 'dart:convert';
  2. import 'dart:typed_data';
  3. import 'package:encrypt/encrypt.dart';
  4. import 'package:pointycastle/asymmetric/pkcs1.dart';
  5. import 'package:pointycastle/asymmetric/rsa.dart';
  6. import 'package:pointycastle/pointycastle.dart';
  7. import '../values/index.dart';
  8. class RSACryptUtil {
  9. ///
  10. ///RSA 加密
  11. ///
  12. static Future<String> encodeString(
  13. String content, String publicKeyStr) async {
  14. // O2OA后端生成的public Key 没有 PEM 头 所以添加O2.RSA_PEM_KEY_HEADER
  15. RSAPublicKey publicKey = await _parseKeyFromString(O2.rasPemKeyHeader+publicKeyStr);
  16. var cipher = PKCS1Encoding(RSAEngine());
  17. cipher.init(true, PublicKeyParameter<RSAPublicKey>(publicKey));
  18. Uint8List output = cipher.process(utf8.encode(content) as Uint8List);
  19. var base64EncodedText = base64Encode(output);
  20. return base64EncodedText;
  21. }
  22. static Future<T> _parseKeyFromString<T extends RSAAsymmetricKey>(
  23. String publicKeyStr) async {
  24. final parser = RSAKeyParser();
  25. return parser.parse(publicKeyStr) as T;
  26. }
  27. }
  28. // void main() async {
  29. // debugPrint('开始啦啦啦啦啦。');
  30. // String key = await RSACryptUtil.encodeString('这里是内容xxxxxxxx',
  31. // 'MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQCWcVZIS57VeOUzi8c01WKvwJK9uRe6hrGTUYmF6J/pI6/UvCbdBWCoErbzsBZOElOH8Sqal3vsNMVLjPYClfoDyYDaUlakP3ldfnXJzAFJVVubF53KadG+fwnh9ZMvxdh7VXVqRL3IQBDwGgzX4rmSK+qkUJjc3OkrNJPB7LLD8QIDAQAB');
  32. // debugPrint(key);
  33. // }