initializeChacha static method

void initializeChacha(
  1. Uint32List state, {
  2. required List<int> key,
  3. required List<int> nonce,
  4. int keyStreamIndex = 0,
})

Implementation

static void initializeChacha(
  Uint32List state, {
  required List<int> key,
  required List<int> nonce,
  int keyStreamIndex = 0,
}) {
  if (key.length > 32) {
    throw ArgumentError('Invalid key');
  }
  if (nonce.length > 12) {
    throw ArgumentError('Invalid nonce');
  }
  state[0] = 0x61707865;
  state[1] = 0x3320646e;
  state[2] = 0x79622d32;
  state[3] = 0x6b206574;

  final stateByteData = ByteData.view(
    state.buffer,
    state.offsetInBytes,
    64,
  );

  //
  // Key
  //
  var stateBytesIndex = 16;
  for (var i = 0; i < key.length; i++) {
    stateByteData.setUint8(stateBytesIndex, key[i]);
    stateBytesIndex++;
  }

  //
  // Counter
  //
  state[12] = keyStreamIndex ~/ 64;

  //
  // Nonce
  //
  for (var i = 13; i < 16; i++) {
    state[i] = 0;
  }
  stateBytesIndex = 13 * 4;
  for (var i = 0; i < nonce.length; i++) {
    stateByteData.setUint8(stateBytesIndex, nonce[i]);
    stateBytesIndex++;
  }

  // In big endian platforms, convert little endian --> host endian
  if (Endian.host != Endian.little) {
    for (var i = 4; i < 12; i++) {
      state[i] = stateByteData.getUint32(4 * i, Endian.little);
    }
    for (var i = 13; i < 16; i++) {
      state[i] = stateByteData.getUint32(4 * i, Endian.little);
    }
  }
}