Skip to content

Add HKDF (SHA256)-Expand #128

Open
Open

Description

@awaik

HKDF is a key derivation function
that has two parts: first "extract" and second "expand". For some encryption tasks, we need only the expand part.
I made a code for that for my project and, I guess, it would be great to add to the lib.

  Future<SecretKey> expandKey({
    required SecretKey secretKey,
    List<int> info = const <int>[],
  }) async {
    // T(0)
    var bytes = const <int>[];

    // T(1), T(2), ...
    final hashLength = hmac.hashAlgorithm.hashLengthInBytes;
    final n = outputLength ~/ hashLength;
    final result = Uint8List(outputLength);
    for (var i = 0; i <= n; i++) {
      final sink = await hmac.newMacSink(secretKey: secretKey);
      sink.add(bytes);
      if (info.isNotEmpty) {
        sink.add(info);
      }
      final added = <int>[0xFF & (1 + i)];
      sink.add(added);
      sink.close();
      final mac = await sink.mac();
      bytes = mac.bytes;
      final offset = i * hashLength;
      if (offset + bytes.length <= result.length) {
        result.setAll(offset, bytes);
      } else {
        result.setAll(offset, bytes.take(result.length - offset));
      }
    }
    return SecretKey(result);
  }

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