dartencryptionpointycastle

"AES engine not initialised" with pointycastle SecureRandom()


I want to generate a random BigInt with dynamik length Bits. I am using the pointycastle package to get a 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;
}

This line throws an exception:

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

This is the complete error in the console:

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)


I can't seem to find a solution to this error message anywhere else. I hope u guys can help me. :D


Solution

  • It is not clear but if I look at the examples from the project it seems like you need to call the seed method. The following works for me:

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

    The example I was inspired by: https://github.com/PointyCastle/pointycastle/blob/master/tutorials/examples/import-demo/import-demo-1.dart