Using modes of operation - ivan-zaera/cipher GitHub Wiki

To use a block cipher with a mode of operation for encryption 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 iv = new Uint8List.fromList( [0x00,0x11,0x22,0x33,0x44,0x55,0x66,0x77,0x88,0x99,0xAA,0xBB,0xCC,0xDD,0xEE,0xFF] );
    var params = new ParametersWithIV(kparams, iv);
    
    var cipher = new BlockCipher( "AES/CBC" )
      ..init( true, params )
    ;

    var plainText = inputPlainText();
    
    var cipherText = cipher.process( plainText );

    outputCipherText( cipherText );

In general, you construct the BlockCipher with the factory constructor which receives the standard algorithm name plus the mode of operation (in the example: AES is the algorithm name, and CBC the mode of operation) and then init() the cipher 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/CBC) it consists of an IV to be consumed by CBC 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 encrypt you make a call to process() with the plain text and the cipher text buffer is returned. Alternatively, if you want more performance, you can use the processBlock() method which doesn't create the output buffer. As opposed to raw block ciphers, you don't need the buffers passed to process() to be of the corresponding block size. If the blocks are larger, this condition is automatically managed by the mode of operation chaining successive calls to processBlock() in the insides. Nevertheless, the need for blocks of the same size as the algorithm block size is still true for the low level processBlock() method.

To decrypt you also use process() or processBlock() but pass false as the first parameter when calling init().

Finally, you can reset an algorithm to its initial state with the reset() method.