google / google/webcrypto.dart

bug: native HMAC imports accept zero-length key material

Open Beginner friendly
#363 0 comments 0 reactions 0 assignees View on GitHub
Dominant language
Dart
Stars
116
Forks
110
Avg merge
6d 8h
Merged PRs (30d)
9

Description

### 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

```dart
import 'package:webcrypto/webcrypto.dart';

Future 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:

```text
0
32
0
32
```

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

Current Chrome rejects both imports with:

```text
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.

Contributor guide

Open the contributing guide

Research direction

Locate the native hmacSecretKey_importRawKey helper and trace how HmacSecretKey.importJsonWebKey reaches it after decoding k. Add regression coverage for empty raw and JWK imports on native and browser backends, then verify both reject zero-length material with FormatException while non-empty keys retain their existing behavior.

Written by the indexing model from the issue text.

Assessment

Tech stack
dart
Domain
cryptography, security
Issue type
Bug
Difficulty
2/5
Estimated time
1-3 hours
Activity status
Quiet
Clarity
Clearly specified
Newbie friendliness
78/100

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.