digest method

Uint8List digest(
  1. String algorithmName,
  2. Uint8List data
)
inherited

Digests data with algorithmName, as OpenSSL names it: sha256, sha512, sha3-256, … The DigestAlgorithm constants are these names with the spelling checked by the compiler, and go in the same place: digest(DigestAlgorithm.sha256, data).

digestHex returns the same as lowercase hexadecimal.

Implementation

Uint8List digest(String algorithmName, Uint8List data) {
  final state = _digestState;
  // Throws for an unknown algorithm, and leaves the working context ready.
  state.beginDigest(algorithmName);
  final ctx = state.workContext;

  final arena = Arena();
  try {
    if (data.isNotEmpty) {
      final dataPtr = arena<UnsignedChar>(data.length);
      dataPtr.cast<Uint8>().asTypedList(data.length).setAll(0, data);

      if (bindings.EVP_DigestUpdate(ctx, dataPtr.cast(), data.length) != 1) {
        throw OpenSslException('EVP_DigestUpdate failed');
      }
    }

    final outPtr = arena<UnsignedChar>(64); // Longest digest OpenSSL emits.
    final outLenPtr = arena<UnsignedInt>(1);

    if (bindings.EVP_DigestFinal_ex(ctx, outPtr, outLenPtr) != 1) {
      throw OpenSslException('EVP_DigestFinal_ex failed');
    }

    return Uint8List.fromList(
        outPtr.cast<Uint8>().asTypedList(outLenPtr.value));
  } finally {
    arena.releaseAll();
  }
}