Skip to content

bug: native HMAC imports accept zero-length key material #363

Description

@harrshita123

Description

The native FFI backend accepts zero-length HMAC key material through both HmacSecretKey.importRawKey and HmacSecretKey.importJsonWebKey.

This differs from browser Web Crypto implementations and from the HMAC import algorithm in the Web Crypto specification, which requires a DataError when the decoded key material has a length of zero.

Accepting an empty key also allows callers to construct a predictable, zero-entropy HMAC key and produce valid-looking signatures without receiving an error.

Reproduction

import 'package:webcrypto/webcrypto.dart';

Future<void> main() async {
  final rawKey = await HmacSecretKey.importRawKey(
    const [],
    Hash.sha256,
  );

  print((await rawKey.exportRawKey()).length);
  print((await rawKey.signBytes(const [1, 2, 3])).length);

  final jwkKey = await HmacSecretKey.importJsonWebKey(
    const {
      'kty': 'oct',
      'alg': 'HS256',
      'use': 'sig',
      'k': '',
    },
    Hash.sha256,
  );

  print((await jwkKey.exportRawKey()).length);
  print((await jwkKey.signBytes(const [1, 2, 3])).length);
}

On the native backend this prints:

0
32
0
32

Both empty keys are accepted and can produce HMAC-SHA-256 signatures.

Current Chrome rejects both imports with:

DataError: HMAC key data must not be empty

Expected behavior

Both raw and JWK imports should reject decoded key material whose length is zero. Consistent with the package's DOM exception mapping, this should surface as a FormatException.

Actual behavior

hmacSecretKey_importRawKey constructs _HmacSecretKeyImpl without checking whether keyData is empty. The JWK path decodes k and delegates to the same helper, so an empty "k" value is accepted as well.

Suggested fix

  • Reject empty keyData in the native HMAC import helper before constructing _HmacSecretKeyImpl.
  • Add regression tests covering empty raw and JWK imports.
  • Require the expected FormatException on native and browser backends.
  • Preserve all existing behavior for non-empty HMAC keys.

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