sha256Sync function

String sha256Sync(
  1. String text
)

Compute SHA-256 synchronously using Process.runSync.

Implementation

String sha256Sync(String text) {
  final result = Process.runSync('sh', [
    '-c',
    'printf "%s" "\$1" | shasum -a 256',
    '--',
    text,
  ], stdoutEncoding: utf8);
  if (result.exitCode == 0) {
    return (result.stdout as String).split(' ').first.trim();
  }
  // Fallback to openssl
  final r2 = Process.runSync('sh', [
    '-c',
    'printf "%s" "\$1" | openssl dgst -sha256 -hex',
    '--',
    text,
  ], stdoutEncoding: utf8);
  final output = (r2.stdout as String).trim();
  // openssl may prefix with "(stdin)= "
  final idx = output.indexOf('= ');
  return idx >= 0 ? output.substring(idx + 2).trim() : output;
}