Skip to content
Open
Show file tree
Hide file tree
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
65 changes: 65 additions & 0 deletions lib/src/testing/regression/issue_302_hmac_jwk_length.dart
Original file line number Diff line number Diff line change
@@ -0,0 +1,65 @@
// 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';

void main() => tests().runTests();

List<({String name, Future<void> Function() test})> tests() {
final tests = <({String name, Future<void> Function() test})>[];
void test(String name, Future<void> Function() fn) =>
tests.add((name: name, test: fn));

test('Hmac: importJsonWebKey honors length', () async {
final keyData = [0xff, 0xe0];
final jwk = {'kty': 'oct', 'alg': 'HS256', 'k': '_-A'};

final rawKey = await HmacSecretKey.importRawKey(
keyData,
Hash.sha256,
length: 9,
);
final jwkKey = await HmacSecretKey.importJsonWebKey(
jwk,
Hash.sha256,
length: 9,
);

check(
equalBytes(await rawKey.exportRawKey(), await jwkKey.exportRawKey()),
'JWK import should zero unused bits the same way as raw import',
Comment thread
harrshita123 marked this conversation as resolved.
);

final data = [1, 2, 3, 4];
check(
equalBytes(await rawKey.signBytes(data), await jwkKey.signBytes(data)),
'JWK import should use the requested HMAC key length for signing',
);
});

test('Hmac: importJsonWebKey validates length', () async {
final jwk = {'kty': 'oct', 'alg': 'HS256', 'k': '_-A'};

bool threw = false;
try {
await HmacSecretKey.importJsonWebKey(jwk, Hash.sha256, length: 7);
} on ArgumentError {
threw = true;
}
check(threw, 'Should throw ArgumentError for invalid HMAC key length');
});

return tests;
}
2 changes: 2 additions & 0 deletions lib/src/testing/testing.dart
Original file line number Diff line number Diff line change
Expand Up @@ -30,6 +30,7 @@ import 'webcrypto/rsassapkcs1v15.dart' as rsassapkcs1v15;
// Other test files, that don't use TestRunner
import 'webcrypto/random.dart' as random;
import 'webcrypto/digest.dart' as digest;
import 'regression/issue_302_hmac_jwk_length.dart' as issue_302_hmac_jwk_length;
import 'regression/issue_60_trailing_bytes.dart' as issue_60_trailing_bytes;

/// Test runners from all test files except `digest.dart` and
Expand Down Expand Up @@ -59,6 +60,7 @@ void runAllTests(
for (final r in _testRunners) ...r.tests(),
...random.tests(),
...digest.tests(),
...issue_302_hmac_jwk_length.tests(),
...issue_60_trailing_bytes.tests(),
];

Expand Down
57 changes: 31 additions & 26 deletions lib/src/webcrypto/webcrypto.hmac.dart
Original file line number Diff line number Diff line change
Expand Up @@ -53,6 +53,30 @@ final class HmacSecretKey {

HmacSecretKey._(this._impl); // keep the constructor private.

static void _checkLength(int length, int keyDataLength) {
if (length > keyDataLength * 8) {
throw ArgumentError.value(
length,
'length',
'must be less than number of bits in keyData',
);
}
if (length <= (keyDataLength - 1) * 8) {
throw ArgumentError.value(
length,
'length',
'must be greater than number of bits in keyData - 8, you can attain '
'the same effect by removing bytes from keyData',
);
}
}

static List<int> _decodeBase64UrlNoPadding(String unpadded) {
final end = unpadded.length;
final pad = (4 - end % 4) % 4;
return base64Url.decode(unpadded.padRight(end + pad, '='));
}

/// Import [HmacSecretKey] from raw [keyData].
///
/// Creates an [HmacSecretKey] using [keyData] as secret key, and running
Expand Down Expand Up @@ -82,20 +106,8 @@ final class HmacSecretKey {
}) async {
// These limitations are given in Web Cryptography Spec:
// https://www.w3.org/TR/WebCryptoAPI/#hmac-operations
if (length != null && length > keyData.length * 8) {
throw ArgumentError.value(
length,
'length',
'must be less than number of bits in keyData',
);
}
if (length != null && length <= (keyData.length - 1) * 8) {
throw ArgumentError.value(
length,
'length',
'must be greater than number of bits in keyData - 8, you can attain '
'the same effect by removing bytes from keyData',
);
if (length != null) {
_checkLength(length, keyData.length);
}

final impl = await webCryptImpl.hmacSecretKey.importRawKey(
Expand Down Expand Up @@ -162,26 +174,19 @@ final class HmacSecretKey {
Hash hash, {
int? length,
}) async {
/*
TODO: Validate these in the native implememtation
// These limitations are given in Web Cryptography Spec:
// https://www.w3.org/TR/WebCryptoAPI/#hmac-operations
if (length != null && length > keyData.length * 8) {
throw ArgumentError.value(
length, 'length', 'must be less than number of bits in keyData');
}
if (length != null && length <= (keyData.length - 1) * 8) {
throw ArgumentError.value(
if (length != null && jwk['k'] is String) {
_checkLength(
Comment thread
harrshita123 marked this conversation as resolved.
Outdated
length,
'length',
'must be greater than number of bits in keyData - 8, you can attain '
'the same effect by removing bytes from keyData',
_decodeBase64UrlNoPadding(jwk['k'] as String).length,
);
}*/
}

final impl = await webCryptImpl.hmacSecretKey.importJsonWebKey(
jwk,
hash._impl,
length: length,
);

return HmacSecretKey._(impl);
Expand Down
Loading