#!/bin/bash
# usage: randomtoken [bytes] [mode]
# modes: hex, md5, sha1, sha256, sha512, base64, raw
# Example randomtoken 32 hex
# requires xxd

# handle args and defaults
if [ "$#" -ne 2 ]; then
    echo "Usage: $0 [bytes] [mode]"
    echo "Modes: hex, md5, sha1, sha256, sha512, base64, raw"
    echo "Example: $0 32 hex"
    exit 1
else
    bytes=$1
    mode=$2
fi

# generate token
if [ "$mode" = "sha256" ]; then
    dd if=/dev/urandom bs=1 count=$bytes status=none | sha256sum | awk '{print $1}'
elif [ "$mode" = "sha512" ]; then
    dd if=/dev/urandom bs=1 count=$bytes status=none | sha512sum | awk '{print $1}'
elif [ "$mode" = "sha1" ]; then
    dd if=/dev/urandom bs=1 count=$bytes status=none | sha1sum | awk '{print $1}'
elif [ "$mode" = "md5" ]; then
    dd if=/dev/urandom bs=1 count=$bytes status=none | md5sum | awk '{print $1}'
elif [ "$mode" = "base64" ]; then
    dd if=/dev/urandom bs=1 count=$bytes status=none | base64 | awk '{print $1}'
elif [ "$mode" = "raw" ]; then
    dd if=/dev/urandom bs=1 count=$bytes status=none
elif [ "$mode" = "hex" ]; then
    dd if=/dev/urandom bs=1 count=$bytes status=none | xxd -p
else
    echo "Unknown mode: $mode"
    exit 1
fi