Using entropy and random numbers - ivan-zaera/cipher GitHub Wiki

This section explains how to get true random numbers and cryptographically secure pseudo random numbers from cipher.

Retrieve secure pseudo random numbers

To use a cryptographically secure pseudo random number generator (CSPRNG) you can use the following code:

    var key = new Uint8List.fromList(
      [0x00,0x11,0x22,0x33,0x44,0x55,0x66,0x77,0x88,0x99,0xAA,0xBB,0xCC,0xDD,0xEE,0xFF] 
    );
    var kparams = new KeyParameter( key );
    var params = new ParametersWithIV(kparams, new Uint8List(16));
    
    var rnd = new SecureRandom("AES/CTR/PRNG")
      ..seed( params )
    ;

    var randomBytes = rnd.nextBytes( 256 );
    
    outputRandomBytes( randomBytes );

In general, you construct the SecureRandom with the factory constructor which receives the standard algorithm name and then seed() the CSPRNG with its corresponding CipherParameters. See Algorithm nomenclature for documentation on standard algorithm names.

The type of CipherParameters to be used depends on the algorithm. For the example (AES/CTR/PRNG) it consists of an IV to be consumed by SIC and a secret key to be used by AES, but, for other algorithms, it can change. See the Table of provided algorithms to get information on which CipherParameters to use for the algorithm of your choice.

To get random data you make calls to nextUint8(), nextUint16(), nextUint32(), nextBigInteger(), or nextBytes().

Retrieve true random numbers

To get true random numbers you must use an EntropySource instance. Due to the physical nature of entropy sources, the interface to get random data is asynchronous. This means that the methods don't return until enough entropy is available which, for some systems, can represent a long time. Thus, it is ususal to use EntropySource to get true random data that it is after used to seed a CSPRNG (i.e: a SecureRandom in cipher's terminology), which is then used to derive a bigger amount of secure random numbers.

To use an EntropySource you can use the following code:

    var source = new EntropySource("file:///dev/random");

    return source.getBytes(256).then( (bytes) {

      outputRandomBytes( bytes );
      
    });

WARNING: As of today it is a bit problematic to obtain true random numbers in Dart. This is due to the lack of an API to retrieve entropy from the native system. For Unix servers, there's an EntropySource that can read from /dev/random, but for Windows there's nothing yet. In the client side there's an EntropySource that can read from a URL (like for example https://www.random.org) but that's definitely not a safe source of entropy, so it shouldn't be used for purposes other than testing or toy implementations. If you decide to use it, do it at your own risk.