Skip to content

Instantly share code, notes, and snippets.

@samanzamani
Created September 10, 2025 09:25
Show Gist options
  • Save samanzamani/19439b4ba0a211bb915b91238556a7b1 to your computer and use it in GitHub Desktop.
Save samanzamani/19439b4ba0a211bb915b91238556a7b1 to your computer and use it in GitHub Desktop.
This script generates the SMS Retriever API hash code required by Android applications.
#!/bin/sh
set -euf
VERSION=0.1.1
USAGE="Usage: sms_retriever_hash.sh --package <package_name> --keystore <keystore_file>"
# --- helpers ---
die() { printf '%s\n' "Error: $*" >&2; exit 1; }
need() { command -v "$1" >/dev/null 2>&1 || die "Missing dependency: $1"; }
# --- parse args ---
pkg=""
keystore=""
while [ "$#" -gt 0 ]; do
case "$1" in
--package)
[ "$#" -ge 2 ] || die "Missing value for --package"
pkg=$2; shift 2 ;;
--keystore)
[ "$#" -ge 2 ] || die "Missing value for --keystore"
keystore=$2; shift 2 ;;
-h|--help)
printf '%s\n' "$USAGE"; exit 0 ;;
*)
die "Unknown argument: $1";;
esac
done
[ -n "${pkg}" ] || die "Package name is required. $USAGE"
[ -n "${keystore}" ] || die "Keystore file is required. $USAGE"
# reject paths that start with '-'
case "$keystore" in
-*) die "Keystore path must not start with '-'";;
esac
# --- dependencies ---
need keytool
need sed
need tr
need xxd
need shasum
need base64
need awk
need cut
# macOS vs GNU base64 flag
if base64 --help 2>/dev/null | grep -q -- '--decode'; then
B64_DEC='--decode'
else
B64_DEC='-D'
fi
# --- validations ---
[ -f "$keystore" ] || die "File not found: $keystore"
printf '\npackage name: %s\nkeystore file: %s\n\n' "$pkg" "$keystore"
# --- extract certificate (hex) safely ---
# Pull PEM body between BEGIN/END CERTIFICATE, remove spaces/newlines, base64-decode, then to hex
cert_hex=$(
keytool -list -rfc -keystore "$keystore" 2>/dev/null \
| awk '/BEGIN CERTIFICATE/{f=1;next} /END CERTIFICATE/{f=0} f' \
| tr -d ' \n' \
| base64 $B64_DEC \
| xxd -p -c 256 \
| tr -d ' \n'
)
[ -n "$cert_hex" ] || die "Failed to extract certificate from keystore (wrong password or invalid keystore?)"
printf '\ncertificate in hex: %s\n' "$cert_hex"
# --- compute SHA-256 over "pkg + space + cert_hex" ---
input="${pkg} ${cert_hex}"
sha256_hex=$(printf '%s' "$input" | shasum -a 256 | cut -c1-64)
printf '\nSHA-256 output in hex: %s\n' "$sha256_hex"
# first 18 hex chars (9 bytes)
first18=$(printf '%s' "$sha256_hex" | cut -c1-18)
# convert to bytes then base64 and take first 11 chars
hash11=$(printf '%s' "$first18" | xxd -r -p | base64 | cut -c1-11)
printf '\nFirst 8 bytes encoded by base64: %s\n' "$hash11"
printf '\nSMS Retriever hash code: %s\n\n' "$hash11"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment