init method

  1. @override
void init(
  1. bool forEncryption,
  2. CipherParameters params
)
override

Implementation

@override
void init(bool forEncryption, CipherParameters params) {
  KeyParameter initKeyParam;
  Uint8List? initNonce;
  CipherParameters chacha20Params;

  if (params is AEADParameters) {
    var aeadParams = params;

    var macSizeBits = aeadParams.macSize;
    if ((MAC_SIZE * 8) != macSizeBits) {
      throw ArgumentError('Invalid value for MAC size: $macSizeBits');
    }

    initKeyParam = aeadParams.parameters as KeyParameter;
    initNonce = aeadParams.nonce;
    chacha20Params = ParametersWithIV(initKeyParam, initNonce);

    _initialAAD = aeadParams.associatedData;
  } else if (params is ParametersWithIV) {
    var ivParams = params;

    initKeyParam = ivParams.parameters as KeyParameter;
    initNonce = ivParams.iv;
    chacha20Params = ivParams;

    _initialAAD = null;
  } else {
    throw ArgumentError('invalid parameters passed to ChaCha20Poly1305');
  }

  // Validate key
  if (KEY_SIZE != initKeyParam.key.length) {
    throw ArgumentError('Key must be 256 bits');
  }

  // Validate nonce
  if (NONCE_SIZE != initNonce.length) {
    throw ArgumentError('Nonce must be 96 bits');
  }

  utils.arrayCopy(initKeyParam.key, 0, _key, 0, KEY_SIZE);

  utils.arrayCopy(initNonce, 0, _nonce, 0, NONCE_SIZE);

  chacha20.init(true, chacha20Params as ParametersWithIV<KeyParameter>);

  _state = forEncryption ? State.ENC_INIT : State.DEC_INIT;

  resetBool(true, false);
}