如何在Dart中填写cipher.doFinal()方法的必需参数?

时间:2019-05-22 12:41:39

标签: java android encryption dart flutter

我正在尝试使用pointy_castle软件包在Flutter应用程序中进行加密,该软件包类似于Java中的crypto.Cipher库。在Java中,有一种名为doFinal()的方法,您可以分配一个参数。在Dart中,您必须分配四个参数。那么如何正确填写所需的参数?我需要一个有关如何执行此操作的示例。

在文档包中,doFinal(Uint8List inp, int inpOff, Uint8List out, int outOff) → int

这是Java中的代码:

 ...
    byte[] encrypted;
    encrypted = cipher.doFinal(padString(text).getBytes());
    String finalData = bytesToHex(encrypted);
    return finalData;
 ...

在Dart中:

...
    Uint8List encrypted; // <- I have to make it of type Uint8List because _bytesToHex method requires looping through the list. However, it produces an error because of that: `A value of type 'int' can't be assigned to a variable of type 'Uint8List'.`
    encrypted = cipher.doFinal(utf8.encode(_padString(data))); // <- This produces an error since doFinal() requires 4 params.
    String finalData = _bytesToHex(encrypted);
    return finalData;
...

1 个答案:

答案 0 :(得分:0)

如果有人遇到这种情况。这就是我最终得到的:

import 'package:pointycastle/export.dart';

class Example {
  Uint8List encrypt(String data) {
    if (data == null || data.length == 0) return null;
    final Uint8List _key = utf8.encode('key');
    final Uint8List _iv = utf8.encode('iv');
    try {
      Uint8List encrypted;
      final CipherParameters params = PaddedBlockCipherParameters(
        ParametersWithIV(
          KeyParameter(_key),
          _iv,
        ),
        null,
      );
      final PaddedBlockCipherImpl cipher = PaddedBlockCipherImpl(
        PKCS7Padding(),
        CBCBlockCipher(
          AESFastEngine(),
        ),
      );
      cipher.init(true, params);
      encrypted = cipher.process(utf8.encode(data));
      return encrypted;
    } catch (_) {
      print(_);
      return null;
    }
  }

  String decrypt(Uint8List data) {
    if (data == null || data.length == 0) return null;
    final Uint8List _key = utf8.encode('key');
    final Uint8List _iv = utf8.encode('iv');
    try {
      final CipherParameters params = PaddedBlockCipherParameters(
        ParametersWithIV(
          KeyParameter(_key),
          _iv,
        ),
        null,
      );
      final PaddedBlockCipherImpl cipher = PaddedBlockCipherImpl(
        PKCS7Padding(),
        CBCBlockCipher(
          AESFastEngine(),
        ),
      );
      cipher.init(false, params);
      final String finalData = utf8.decode(cipher.process(data));
      return finalData;
    } catch (_) {
      print(_);
      return null;
    }
  }
}

感谢https://stackoverflow.com/users/9014097/topacohttps://github.com/Nguyenpk57的启发。