"AES engine not initialised" 使用 pointycastle SecureRandom()

"AES engine not initialised" with pointycastle SecureRandom()

我想生成一个具有动态长度位的随机 BigInt。我正在使用 pointycastle 包来获取 SecureRandom BigInt。

import 'package:pointycastle/pointycastle.dart';

void main(List<String> arguments) {
  print(gen(500));
}

BigInt gen(int Bits) {
  var n = BigInt.from(1);
  var ran = SecureRandom('Fortuna');
  n = ran.nextBigInteger(Bits);
  return n;
}

这一行抛出异常:

n = ran.nextBigInteger(Bits);
StateError (Bad state: AES engine not initialised)

这是控制台中的完整错误:

Unhandled exception:
Bad state: AES engine not initialised
#0      AESFastEngine.processBlock 
package:pointycastle/block/aes_fast.dart:109
#1      BlockCtrRandom.nextUint8 
package:pointycastle/random/block_ctr_random.dart:55
#2      SecureRandomBase._randomBits 
package:pointycastle/…/impl/secure_random_base.dart:55

#3      SecureRandomBase.nextBigInteger 
package:pointycastle/…/impl/secure_random_base.dart:33
#4      AutoSeedBlockCtrRandom.nextBigInteger.<anonymous closure> 
package:pointycastle/random/auto_seed_block_ctr_random.dart:69
#5      AutoSeedBlockCtrRandom._autoReseedIfNeededAfter 
package:pointycastle/random/auto_seed_block_ctr_random.dart:81
#6      AutoSeedBlockCtrRandom.nextBigInteger 
package:pointycastle/random/auto_seed_block_ctr_random.dart:68
#7      FortunaRandom.nextBigInteger 
package:pointycastle/random/fortuna_random.dart:46
#8      gen 
bin\encrypt.dart:10
#9      main 
bin\encrypt.dart:4
#10     _startIsolate.<anonymous closure>  (dart:isolate-patch/isolate_patch.dart:299:32)
#11     _RawReceivePortImpl._handleMessage  (dart:isolate-patch/isolate_patch.dart:168:12)


我似乎无法在其他任何地方找到此错误消息的解决方案。我希望你们能帮助我。 :D

欢迎使用 Whosebug。

使用 Pointycastle 的任何部分时,您都需要实例化实现对象。

在您的代码中您正在使用

var ran = SecureRandom('Fortuna');

使用 SecureRandom class。

只需添加

final rnd = new SecureRandom("AES/CTR/PRNG");

请参阅 PointCastle SecureRandom 示例以了解更多问题:

https://github.com/PointyCastle/pointycastle/blob/master/test/random/block_ctr_random_test.dart

不清楚,但如果我查看项目中的示例,似乎您需要调用 seed 方法。以下对我有用:

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

import 'package:pointycastle/pointycastle.dart';

void main(List<String> arguments) {
  print(gen(500));
}

BigInt gen(int bits) {
  final _sGen = Random.secure();
  var n = BigInt.from(1);
  var ran = SecureRandom('Fortuna');
  ran.seed(KeyParameter(
      Uint8List.fromList(List.generate(32, (_) => _sGen.nextInt(255)))));
  n = ran.nextBigInteger(bits);
  return n;
}

我受到启发的例子:https://github.com/PointyCastle/pointycastle/blob/master/tutorials/examples/import-demo/import-demo-1.dart