Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add HKDF (SHA256)-Expand #128

Open
awaik opened this issue Feb 14, 2023 · 0 comments
Open

Add HKDF (SHA256)-Expand #128

awaik opened this issue Feb 14, 2023 · 0 comments

Comments

@awaik
Copy link

awaik commented Feb 14, 2023

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);
  }
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant