lib/hash.sh

635 B · 32 lines · bash

1#!/usr/bin/env bash
2
3brt_hash() {
4 local algo="${1:-sha256}"
5 local input="${2:-}"
6
7 if [[ -z "$input" ]]; then
8 brt_error "Usage: brt -hash <md5|sha1|sha256|sha512> <string|file>"
9 exit 1
10 fi
11
12 algo=$(echo "$algo" | tr '[:upper:]' '[:lower:]')
13
14 local cmd=""
15 case "$algo" in
16 md5) cmd="md5" ;;
17 sha1) cmd="shasum -a 1" ;;
18 sha256) cmd="shasum -a 256" ;;
19 sha512) cmd="shasum -a 512" ;;
20 *)
21 brt_error "Unsupported algorithm: ${algo}"
22 exit 1
23 ;;
24 esac
25
26 if [[ -f "$input" ]]; then
27 $cmd "$input" | awk '{print $1}'
28 else
29 printf '%s' "$input" | $cmd | awk '{print $1}'
30 fi
31}
32