hash method

Result<String> hash(
  1. String value
)
override

Creates a deterministic hash of the input value. The same value will always produce the same hash. Returns Result<String> with base64-encoded hash or error.

Implementation

Result<String> hash(String value) {
  if (secretKey.isEmpty) {
    return Result.error('[InvalidArgument] Secret key is empty');
  }
  if (salt.isEmpty) {
    return Result.error('[InvalidArgument] Salt is empty');
  }
  if (value.isEmpty) {
    return Result.error('[InvalidArgument] Value is empty');
  }
  // Prevent DoS attacks via extremely long inputs
  if (value.length > 10000) {
    return Result.error(
      '[InvalidArgument] Value exceeds maximum length of 10000 characters',
    );
  }

  try {
    // Use HMAC-SHA256 for secure deterministic hashing
    final key = utf8.encode(secretKey);
    final hmac = Hmac(sha256, key);
    // Use separator to prevent collision attacks
    final valueWithSalt = utf8.encode('$value|$salt');
    final digest = hmac.convert(valueWithSalt);

    return Result.value(base64.encode(digest.bytes));
  } catch (e) {
    // Note: Exception details omitted for security.
    // Log internally if needed: logger.error('Hashing failed', error: e);
    return Result.error('[Internal] Hashing failed $e');
  }
}