[英]How to fill the required parameters for cipher.doFinal() method in Dart?
我正在嘗試使用pointy_castle
包在我的Flutter應用程序中進行加密,這類似於Java中的crypto.Cipher
庫。 有一個名為doFinal()
的方法,在Java中,您可以分配一個參數。 在Dart中,您必須分配四個參數。 那么我該如何正確填寫所需的參數呢? 我需要一個如何做到這一點的例子。
在包docs中, 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;
...
在達特:
...
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;
...
如果有人遇到過這種情況。 這就是我最終得到的結果:
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/topaco和https://github.com/Nguyenpk57的靈感。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.