Skip to content

DartChacha20: block counter wraps past 2^32 instead of failing #233

Open

Description

@DicksonWu654

Low-priority finding, not a security issue in practice.

DartChacha20 in cryptography 2.9.0 keeps going past the 32-bit block counter instead of failing. Starting at block 0xffffffff with a 65-byte message, the last byte is encrypted with the keystream for block 0, so the keystream repeats. RFC 8439 §2.3 defines the counter as "A 32-bit block count parameter", so anything past 0xffffffff is out of range. You need about 256 GiB under one key and nonce to hit it, which is why I'd call it low.

Repro (Wycheproof chacha20_counter_test.json tcId 40, expected invalid):

import 'package:cryptography/cryptography.dart';
import 'package:cryptography/dart.dart';

// Wycheproof testvectors_v1/chacha20_counter_test.json tcId=40.
List<int> bytes(String h) => [for (var i = 0; i < h.length; i += 2) int.parse(h.substring(i, i + 2), radix: 16)];

Future<void> main() async {
  final key = bytes('0000000000000000000000000000000000000000000000000000000000000000');
  final nonce = bytes('000000000000000000000000');
  final msg = bytes('0000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000');
  final cipher = DartChacha20(macAlgorithm: MacAlgorithm.empty);
  try {
    final wrapped = await cipher.encrypt(msg, secretKey: SecretKey(key), nonce: nonce, keyStreamIndex: 0xffffffff * 64);
    final counter0 = await cipher.encrypt(<int>[0], secretKey: SecretKey(key), nonce: nonce, keyStreamIndex: 0);
    print('accepted=${wrapped.cipherText.length == 65} bytes=${wrapped.cipherText.length} wrapped_counter0_byte_reused=${wrapped.cipherText[64] == counter0.cipherText[0]}');
  } catch (error) {
    print('rejected=$error');
  }
}
accepted=true bytes=65 wrapped_counter0_byte_reused=true

Throwing once the block counter would pass 0xffffffff would match the RFC.

Found while running the Wycheproof vectors against a set of crypto libraries

Activity

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions