diff --git a/lib/src/impl_ffi/impl_ffi.hmac.dart b/lib/src/impl_ffi/impl_ffi.hmac.dart index f48135d4..cc0b8a07 100644 --- a/lib/src/impl_ffi/impl_ffi.hmac.dart +++ b/lib/src/impl_ffi/impl_ffi.hmac.dart @@ -37,6 +37,7 @@ Future hmacSecretKey_importRawKey( HashImpl hash, { int? length, }) async { + _checkData(keyData.isNotEmpty, message: 'HMAC key data must not be empty'); return _HmacSecretKeyImpl( _asUint8ListZeroedToBitLength(keyData, length), _HashImpl.fromHash(hash), diff --git a/lib/src/testing/regression/hmac_empty_key.dart b/lib/src/testing/regression/hmac_empty_key.dart new file mode 100644 index 00000000..72281376 --- /dev/null +++ b/lib/src/testing/regression/hmac_empty_key.dart @@ -0,0 +1,45 @@ +// Copyright 2026 Google LLC +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +import 'package:webcrypto/webcrypto.dart'; + +import '../utils/utils.dart'; + +List<({String name, Future Function() test})> tests() => [ + ( + name: 'HMAC rejects empty raw keys', + test: () => _expectEmptyKeyRejected( + HmacSecretKey.importRawKey(const [], Hash.sha256), + ), + ), + ( + name: 'HMAC rejects empty JWK keys', + test: () => _expectEmptyKeyRejected( + HmacSecretKey.importJsonWebKey(const { + 'kty': 'oct', + 'alg': 'HS256', + 'k': '', + }, Hash.sha256), + ), + ), +]; + +Future _expectEmptyKeyRejected(Future import) async { + try { + await import; + } on FormatException { + return; + } + check(false, 'Expected an empty HMAC key to be rejected'); +} diff --git a/lib/src/testing/testing.dart b/lib/src/testing/testing.dart index 35883c10..3a32b92a 100644 --- a/lib/src/testing/testing.dart +++ b/lib/src/testing/testing.dart @@ -75,6 +75,7 @@ void runAllTests( ...jwk_base64url.tests(), ...derive_bits_zero_length.tests(), ...ecdh_invalid_length.tests(), + ...hmac_empty_key.tests(), ...rsa_oaep_sha1_jwk_alg.tests(), ...rsa_modulus_length.tests(), ];