pbkdf2 method

Uint8List pbkdf2({
  1. required Uint8List password,
  2. required Uint8List salt,
  3. int iterations = 10000,
  4. int keyLength = 32,
})
inherited

Deriva uma chave a partir de uma senha usando PBKDF2-HMAC-SHA256.

password: A senha. salt: O salt aleatório. iterations: Número de iterações (default: 10000). keyLength: Tamanho da chave desejada em bytes (default: 32 bytes / 256 bits).

Implementation

Uint8List pbkdf2({
  required Uint8List password,
  required Uint8List salt,
  int iterations = 10000,
  int keyLength = 32,
}) {
  final ctx = bindings.HMAC_CTX_new();
  if (ctx == nullptr) throw OpenSslException('Failed to create HMAC_CTX');

  final messageDigest = bindings.EVP_sha256();
  // SHA256 block size is 32 bytes
  const hLen = 32;

  // ceil(keyLength / hLen)
  final blockCount = (keyLength / hLen).ceil();
  // Buffer for the final result (might be slightly larger than keyLength initially)
  final fullResult = Uint8List(blockCount * hLen);

  final arena = Arena();
  try {
    final passPtr = arena<UnsignedChar>(password.length);
    passPtr.cast<Uint8>().asTypedList(password.length).setAll(0, password);

    // Salt buffer needs space for 4-byte counter appended
    final saltPlusCountPtr = arena<UnsignedChar>(salt.length + 4);
    saltPlusCountPtr.cast<Uint8>().asTypedList(salt.length).setAll(0, salt);

    // Helper for pointers
    final uBlockPtr = arena<UnsignedChar>(hLen); // U_j
    final outLenPtr = arena<UnsignedInt>(1);
    final tBlock = Uint8List(hLen); // T_i accumulator

    // 1. Initialize HMAC with Password as Key.
    // This key will be reused for all iterations.
    if (bindings.HMAC_Init_ex(
            ctx, passPtr.cast(), password.length, messageDigest, nullptr) !=
        1) {
      throw OpenSslException('HMAC_Init_ex failed to set key');
    }

    int resultOffset = 0;

    for (int i = 1; i <= blockCount; i++) {
      // --- Block i ---
      // T_i = F(P, S, c, i) = U_1 ^ U_2 ^ ... ^ U_c

      // 1. Calculate U_1 = PRF(P, S || INT_32_BE(i))

      // Update the counter part of saltPlusCountPtr
      // INT_32_BE(i)
      final iBytes = ByteData(4)..setUint32(0, i, Endian.big);
      final iList = iBytes.buffer.asUint8List();
      final saltSuffixPtr = saltPlusCountPtr + salt.length;
      for (int b = 0; b < 4; b++) {
        (saltSuffixPtr + b).value = iList[b];
      }

      // Run HMAC for U_1
      // Reuse key (pass nullptr)
      if (bindings.HMAC_Init_ex(ctx, nullptr, 0, nullptr, nullptr) != 1) {
        throw OpenSslException('HMAC_Init_ex failed at block $i');
      }
      if (bindings.HMAC_Update(ctx, saltPlusCountPtr, salt.length + 4) != 1) {
        throw OpenSslException('HMAC_Update failed at block $i');
      }
      if (bindings.HMAC_Final(ctx, uBlockPtr, outLenPtr) != 1) {
        throw OpenSslException('HMAC_Final failed at block $i');
      }

      // Copy U_1 to T_i accumulator
      final uList = uBlockPtr.cast<Uint8>().asTypedList(hLen);
      tBlock.setAll(0, uList); // T_i = U_1

      // 2. Loop U_2 ... U_iterations
      for (int j = 2; j <= iterations; j++) {
        // U_j = PRF(P, U_{j-1})
        // Reuse key
        if (bindings.HMAC_Init_ex(ctx, nullptr, 0, nullptr, nullptr) != 1) {
          throw OpenSslException('HMAC_Init_ex failed at iter $j');
        }
        if (bindings.HMAC_Update(ctx, uBlockPtr, hLen) != 1) {
          throw OpenSslException('HMAC_Update failed at iter $j');
        }
        if (bindings.HMAC_Final(ctx, uBlockPtr, outLenPtr) != 1) {
          throw OpenSslException('HMAC_Final failed at iter $j');
        }

        // XOR into T_i
        // uList is now U_j because HMAC_Final writes to uBlockPtr
        for (int k = 0; k < hLen; k++) {
          tBlock[k] ^= uList[k];
        }
      }

      // Block i complete. Append T_i to result.
      fullResult.setRange(resultOffset, resultOffset + hLen, tBlock);
      resultOffset += hLen;
    }

    // 3. Truncate to keyLength
    if (keyLength < fullResult.length) {
      return fullResult.sublist(0, keyLength);
    }
    return fullResult;
  } finally {
    bindings.HMAC_CTX_free(ctx);
    arena.releaseAll();
  }
}