importJsonWebKey static method

Future<HmacSecretKey> importJsonWebKey(
  1. Map<String, dynamic> jwk,
  2. Hash hash,
  3. {int? length}
)

Import HmacSecretKey from JSON Web Key.

The jwk should be given as Map, String, List the same way jsonDecode from dart:convert represents decoded JSON values. The hash algorithm to be used is specified by hash.

JSON Web Keys imported using HmacSecretKey.importJsonWebKey must have "kty": "oct", and the hash given must match the hash algorithm implied by the "alg" property of the imported jwk.

For importing a JWK with:

If specified the "use" property of the imported jwk must be "use": "sig".

Throws FormatException if jwk is invalid.

Example

import 'package:webcrypto/webcrypto.dart';
import 'dart:convert' show jsonEncode, jsonDecode;

// JSON Web Key as a string containing JSON.
final jwk = '{"kty": "oct", "alg": "HS256", "k": ...}';

// Import secret key from decoded JSON.
final key = await HmacSecretKey.importJsonWebKey(
  jsonDecode(jwk),
  Hash.sha256, // Must match the hash used the JWK key "alg"
);

// Export the key (print it in same format as it was given).
Map<String, dynamic> keyData = await key.exportJsonWebKey();
print(jsonEncode(keyData));

Implementation

static Future<HmacSecretKey> importJsonWebKey(
  // TODO: Determine if the "alg" property can be omitted, and update documentation accordingly
  //       also make tests covering cases where "alg" is omitted.
  // TODO: Determine if there is any restrictions on "use" and "key_ops".
  Map<String, dynamic> jwk,
  // TODO: Discuss if hash parameter is really necessary, it's in the JWK.
  //       Presumably webcrypto requires as a sanity check. Notice, that this
  //       should be consistent with other JWK imports, where we specify curve
  //       or other parameters. Either we read from JWK, or we verify that
  //       what is in the JWK matches what is also given.
  //       Note. it's not yet clear if JWK always contains key parameters.
  Hash hash, {
  int? length,
}) {
  /*
  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(
      length,
      'length',
      'must be greater than number of bits in keyData - 8, you can attain '
          'the same effect by removing bytes from keyData',
    );
  }*/

  return impl.hmacSecretKey_importJsonWebKey(jwk, hash, length: length);
}