Skip to content

DartAesGcm: counter increment carries past the low 32 bits (GCM inc32) #234

Open

Description

@DicksonWu654

Low-priority interop finding, not a security issue.

DartAesGcm in cryptography 2.9.0 increments the whole 128-bit counter block between blocks. GCM only increments the low 32 bits (NIST SP 800-38D §6.2 inc32: "the remaining, left-most len(X)-s bits remain unchanged", with s = 32). The two only differ when the low word wraps. With a 96-bit nonce that never happens in practice, but with other nonce lengths J0 comes from GHASH and can land near ffffffff in the low word, and then Dart produces a different keystream from every other GCM implementation.

Repro (Wycheproof aes_gcm_test.json tcId 79, a valid case where J0 = ffffffffffffffffffffffffffffffff). The tag verifies, but the plaintext is wrong:

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

// Wycheproof testvectors_v1/aes_gcm_test.json tcId=79 (J0: ffffffffffffffffffffffffffffffff).
List<int> bytes(String h) => [for (var i = 0; i < h.length; i += 2) int.parse(h.substring(i, i + 2), radix: 16)];
String hex(List<int> x) => x.map((b) => b.toRadixString(16).padLeft(2, '0')).join();

Future<void> main() async {
  final key = bytes('00112233445566778899aabbccddeeff');
  final iv = bytes('1a552e67cdc4dc1a33b824874ebf0bed');
  final ct = bytes('948ca37a8e6649e88aeffb1c598f3607007702417ea0e0bc3c60ad5a949886de968cf53ea6462aed');
  final tag = bytes('99b381bfa2af9751c39d1b6e86d1be6a');
  final expected = bytes('00000000000000000000000000000000000000000000000000000000000000000000000000000000');
  try {
    final actual = await DartAesGcm(secretKeyLength: key.length, nonceLength: iv.length).decrypt(
      SecretBox(ct, nonce: iv, mac: Mac(tag)), secretKey: SecretKey(key), aad: const <int>[]);
    print('accepted=true plaintext_matches_vector=${hex(actual) == hex(expected)} plaintext=${hex(actual)}');
  } catch (error) {
    print('accepted=false error=$error');
  }
}
accepted=true plaintext_matches_vector=false plaintext=696858d4c46fa9c86518d98ac60cb52c84a3cb81f5efa8945d83049c57c342078b75d209e3559539

Same thing for tcIds 79-84, 159-164 and 242-247. The fix should just be incrementing the last 4 bytes of the counter block mod 2^32 and leaving the first 12 alone.

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