How to convert encrypt java code below in flutter

I m requirement is to convert below java encrypt code to flutter as i need to encrypt few fields value before sending to api. Below is java encrypt code which i need to convert to java

public static String encrypt(String text, String algo, Key key) {
        byte[] cipherText;
        String output;
        try {
            if("RSA".equals(algo)) {
                throw new IllegalArgumentException("Do not pass just algo pass with padding and blocking stuff!");
            }
            if(BuildConfig.DEBUG) {
                Log.d(TAG, "encrypt in: "+text);
                Log.d(TAG, "algo: "+algo);
                Log.d(TAG, "key: "+key);
            }

            final Cipher cipher = Cipher.getInstance(algo);

            if(algo.contains("AES")) {
                AlgorithmParameterSpec ivSpec = new IvParameterSpec(ivBytes);
                cipher.init(Cipher.ENCRYPT_MODE, key, ivSpec);
            } else {
                cipher.init(Cipher.ENCRYPT_MODE, key);
            }

            cipherText = cipher.doFinal(text.getBytes(StandardCharsets.UTF_8));
            output = new String(Base64.encode(cipherText));

            if(BuildConfig.DEBUG) {
                Log.d(TAG, "encrypt out: "+output);
            }

            return output;
        } catch (Exception e) {
            Log.e(TAG, SDKConstants.STRING_ERROR + e, e);
            return null;
        }
}

            char[] encPwd = Objects.requireNonNull(CryptoHelper.encrypt(Objects.requireNonNull(binding.textIPassword.getEditText()).getText().toString(), CryptoHelper.ALGO_FOR_RSA, key)).toCharArray();

Please help me in converting above java code to flutter as i need to encrypt one field before sending it to api call.

Any help is appreciated!


Just work through the Java line by line and figure out Dart equivalents. Use the other linked question as your guide. This should work (if I guessed the cipher correctly):

import 'package:pointycastle/export.dart';

String encrypt(String plainText, RSAPublicKey public) {
  final plainBytes = utf8.encode(plainText) as Uint8List;

  final cipher = PKCS1Encoding(RSAEngine())
    ..init(true, PublicKeyParameter<RSAPublicKey>(public));
  final cipherBytes = cipher.process(plainBytes);
  return base64Encode(cipherBytes);
}