aboutsummaryrefslogtreecommitdiff
path: root/bin
diff options
context:
space:
mode:
Diffstat (limited to 'bin')
-rwxr-xr-xbin/jwt-decode.sh73
1 files changed, 73 insertions, 0 deletions
diff --git a/bin/jwt-decode.sh b/bin/jwt-decode.sh
new file mode 100755
index 0000000..5e47adf
--- /dev/null
+++ b/bin/jwt-decode.sh
@@ -0,0 +1,73 @@
+#!/bin/sh
+## SPDX-FileCopyrightText: 2022 M. Shulhan <ms@kilabit.info>
+## SPDX-License-Identifier: GPL-3.0-or-later
+
+## depends=(jq openssl)
+
+## Script to decode JWT.
+##
+## Usage:
+##
+## $ jwt_decode.sh $token [$secret]
+##
+## The $secret argument is optional, if its given it will check the signature
+## is matched or not.
+
+base64_decode() {
+ len=$((${#1} % 4))
+ case $len in
+ 2)
+ str="$1"'==' ;;
+ 3)
+ str="$1"'=' ;;
+ *)
+ str="$1" ;;
+ esac
+ echo -n $str | openssl enc -d -a -A
+}
+
+jwt=$1
+secret=$2
+
+if [[ -z $jwt ]]; then
+ echo "Missing token"
+ exit 1
+fi
+
+header_b64=$(echo -n $jwt | cut -d '.' -f 1)
+header=$(base64_decode "$header_b64")
+
+payload_b64=$(echo -n $jwt | cut -d '.' -f 2)
+payload=$(base64_decode "$payload_b64")
+
+sign=$(echo -n $jwt | cut -d '.' -f 3)
+
+expired_at=$(echo $PAY | jq '.exp')
+if [[ -n "$expired_at" ]]; then
+ expired_at=$(date -d @${expired_at} --rfc-3339=seconds)
+fi
+
+issued_at=$(echo $PAY | jq '.iat')
+if [[ -n "$issued_at" ]]; then
+ issued_at=$(date -d @${issued_at} --rfc-3339=seconds)
+fi
+
+echo "Header: $header"
+echo "Payload: $payload"
+echo "Issued at: $issued_at"
+echo "Expired at: $expired_at"
+
+## Check the signature using secret.
+if [[ -n "$secret" ]]; then
+ got_sign=$(echo -n "$header_b64"."$payload_b64" \
+ | openssl dgst -sha256 -hmac secret -binary | base64)
+ got_sign=${got_sign%=}
+
+ if [[ "$sign" == "$got_sign" ]]; then
+ echo "Signature: PASS"
+ else
+ echo "Signature: FAIL"
+ fi
+else
+ echo "Signature: SKIP"
+fi