将Java RSA非对称加密转换为Flutter Dart

5

我正在尝试将我们的安卓手机应用移植到Flutter。 它是用Java编写的。 然而,有这样一部分内容,我需要在将登录凭据和卡片详细信息发布到服务器之前使用RSA加密对其进行加密,但我始终无法正确操作。

我已经尝试了几个Flutter包,但没有成功。 根据Java开发人员的说法,有一个base64编码的公钥需要用于加密密码。

以下是Java代码

public  static  String Encrypt(String plaintext, String publicKey ) throws Exception {
  try
  {

      if(StringUtils.isEmpty(plaintext)) return "";
      byte[] modulusBytes = Base64.decode(publicKey.getBytes("UTF-8"),Base64.DEFAULT);
      byte[] exponentBytes = Base64.decode("AQAB".getBytes("UTF-8"),Base64.DEFAULT);
      BigInteger modulus = new BigInteger(1, modulusBytes );
      BigInteger exponent = new BigInteger(1, exponentBytes);
      RSAPublicKeySpec rsaPubKey = new RSAPublicKeySpec(modulus, exponent);
      KeyFactory fact = KeyFactory.getInstance("RSA");
      PublicKey pubKey = fact.generatePublic(rsaPubKey);

      Cipher cipher = Cipher.getInstance("RSA/ECB/PKCS1PADDING");
      cipher.init(Cipher.ENCRYPT_MODE, pubKey);

      byte[] plainBytes = new String(plaintext).getBytes("UTF-8");
      byte[] cipherData = cipher.doFinal( plainBytes );


      String outputEncrypted = Base64.encodeToString(cipherData,Base64.NO_WRAP);

      return  outputEncrypted;

  }catch (Exception ex)
  {
      Log.i("Exception", ex.getMessage());
      throw  ex;

  }

}

如果能将此内容转换为Dart,以便在Flutter代码中使用,我将不胜感激。

更新

我尝试了@Richard Heap的PointyCastle加密,看起来很好用,但服务器无法解密该字符串。出现异常。

Interop+AppleCrypto+AppleCFErrorCryptographicException: The operation couldn’t be completed. (OSStatus error -2147415994 - CSSMERR_CSP_INVALID_DATA)
   at Interop.AppleCrypto.ExecuteTransform(SecKeyTransform transform)
   at Interop.AppleCrypto.RsaDecrypt(SafeSecKeyRefHandle privateKey, Byte[] data, RSAEncryptionPadding padding)
   at System.Security.Cryptography.RSAImplementation.RSASecurityTransforms.Decrypt(Byte[] data, RSAEncryptionPadding padding)
   at System.Security.Cryptography.RSACryptoServiceProvider.Decrypt(Byte[] rgb, Boolean fOAEP)


Internal.Cryptography.CryptoThrowHelper+WindowsCryptographicException: The parameter is incorrect
   at Internal.NativeCrypto.CapiHelper.DecryptKey(SafeKeyHandle safeKeyHandle, Byte[] encryptedData, Int32 encryptedDataLength, Boolean fOAEP, Byte[]& decryptedData)
   at System.Security.Cryptography.RSACryptoServiceProvider.Decrypt(Byte[] rgb, Boolean fOAEP

服务器上的解密方法是用C#编写的。

更新2

在漫长的谷歌搜索后,我终于把它搞定了。我发现了这个PointyCastle上的github问题,以及duncanhoggan提出的解决方案。结果证明,我只需要使用PKCS1Encoding即可。

  var pubKey = RSAPublicKey(modulus, exponent);
  var cipher = PKCS1Encoding(RSAEngine());
  cipher.init(true, PublicKeyParameter<RSAPublicKey>(pubKey));
  Uint8List output = cipher.process(utf8.encode(text));
  var base64EncodedText = base64Encode(output);
  return base64EncodedText;

@Richard Heap,感谢您的帮助。


你试过Pointy Castle吗?你卡在哪里了? - Richard Heap
1个回答

2

试试这个:

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

import 'package:convert/convert.dart';
import 'package:pointycastle/api.dart';
import 'package:pointycastle/asymmetric/api.dart';
import 'package:pointycastle/asymmetric/rsa.dart';

String encrypt(String plaintext, String publicKey) {
  var modulusBytes = base64.decode(publicKey);
  var modulus = BigInt.parse(hex.encode(modulusBytes), radix: 16);
  var exponent = BigInt.parse(hex.encode(base64.decode('AQAB')), radix: 16);
  var engine = RSAEngine()
    ..init(
      true,
      PublicKeyParameter<RSAPublicKey>(RSAPublicKey(modulus, exponent)),
    );

  //PKCS1.5 padding
  var k = modulusBytes.length;
  var plainBytes = utf8.encode(plaintext);
  var paddingLength = k - 3 - plainBytes.length;
  var eb = Uint8List(paddingLength + 3 + plainBytes.length);
  var r = Random.secure();
  eb.setRange(paddingLength + 3, eb.length, plainBytes);
  eb[0] = 0;
  eb[1] = 2;
  eb[paddingLength + 2] = 0;
  for (int i = 2; i < paddingLength + 2; i++) {
    eb[i] = r.nextInt(254) + 1;
  }

  print(plainBytes.length);
  print(eb);

  return base64.encode(
    engine.process(eb),
  );
}

我在加密方面没有任何问题,但服务器无法解密我的加密字符串。我进行了调试,发现在解密时抛出了异常。我已经更新了我的问题,并附上了异常信息。 - ibnhamza
什么是十六进制值? - Pravin Divraniya
1
@PravinDivraniya hex 是来自 convert 包(注意额外的包导入)的常量值,用于十六进制编解码器。 - Richard Heap
在Flutter中是否有EncodedKeySpec? - Hemavathi
@RichardHeap 我正在尝试将Java代码转换为Flutter,请参考https://stackoverflow.com/questions/70576691/crypto-x509encodedkeyspec-equivalent-code-in-flutter,任何帮助都将不胜感激。 - Hemavathi
显示剩余2条评论

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接