【问题标题】:How to convert encrypt java code below in flutter如何在颤动中转换下面的加密java代码
【发布时间】:2022-01-18 13:05:12
【问题描述】:

我的要求是将下面的 java 加密代码转换为颤振,因为我需要在发送到 api 之前加密几个字段值。 下面是我需要转换成java的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();

请帮助我将上面的 java 代码转换为颤振,因为我需要在将一个字段发送到 api 调用之前对其进行加密。

感谢任何帮助!

【问题讨论】:

  • @Richard Heap 请帮忙把上面的java代码转换成flutter,谢谢
  • Java 中的这个常量是什么? CryptoHelper.ALGO_FOR_RSARSA/ECB/PKCS1吗?如果不是,那是什么?
  • 请注意 Stackoverflow 不是免费的代码转换服务
  • 这几乎涵盖了这里:stackoverflow.com/questions/56473470/…
  • 公共静态最终字符串 ALGO_FOR_RSA = "RSA/ECB/PKCS1Padding";

标签: flutter


【解决方案1】:

只需逐行阅读 Java 并找出 Dart 等价物。使用其他链接的问题作为您的指导。这应该有效(如果我猜对了密码):

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);
}

【讨论】:

  • 请注意,Java 将生成的 base 64 转换为字符。 Dart 中没有真正的等价物。在发送到 API 之前,您必须弄清楚 Java 如何使用这些字符。我将加密的 base 64 保留为字符串。
  • 我会尝试将此字符串传递给 api n 看看 api 是否有效
  • 这就是我将加密密码传递给 setPassword 方法的方式
  • 一切都取决于 Java LoginRequest 的样子。使用Arrays.toString() 似乎很奇怪API 真的想要一个看起来像[a, b, c, d] 而不是abcd 的字符串吗??
  • 在我看来这个问题已经有了答案:how to convert the encrypt method from Java to Dart
猜你喜欢
  • 2019-08-05
  • 1970-01-01
  • 2021-11-03
  • 2015-03-29
  • 2020-11-25
  • 2013-06-23
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多