| 1 |
|
| 2 |
|
| 3 |
ALG="RS256" |
| 4 |
|
| 5 |
while getopts "a:k:s:" opt; do |
| 6 |
case "$opt" in |
| 7 |
k) KEY=$OPTARG ;; |
| 8 |
s) KEY=<(echo -en "$OPTARG") ;; |
| 9 |
a) ALG=$OPTARG ;; |
| 10 |
esac |
| 11 |
done |
| 12 |
|
| 13 |
shift $((OPTIND-1)) |
| 14 |
|
| 15 |
HEADER=$1 |
| 16 |
PAYLOAD=$2 |
| 17 |
|
| 18 |
function b64enc() { openssl enc -base64 -A | tr '+/' '-_' | tr -d '='; } |
| 19 |
|
| 20 |
function convert_ec { |
| 21 |
INPUT=$(openssl asn1parse -inform der) |
| 22 |
R=$(echo "$INPUT" | head -2 | tail -1 | cut -d':' -f4) |
| 23 |
S=$(echo "$INPUT" | head -3 | tail -1 | cut -d':' -f4) |
| 24 |
|
| 25 |
echo -n $R | xxd -r -p |
| 26 |
echo -n $S | xxd -r -p |
| 27 |
} |
| 28 |
|
| 29 |
function rs_sign() { openssl dgst -binary -sha${1} -sign "$2"; } |
| 30 |
function es_sign() { openssl dgst -binary -sha${1} -sign "$2" | convert_ec; } |
| 31 |
|
| 32 |
JWT_HDR_B64="$(echo -n "$HEADER" | b64enc)" |
| 33 |
JWT_PAY_B64="$(echo -n "$PAYLOAD" | b64enc)" |
| 34 |
UNSIGNED_JWT="$JWT_HDR_B64.$JWT_PAY_B64" |
| 35 |
|
| 36 |
case "$ALG" in |
| 37 |
RS*) SIGNATURE=$(echo -n "$UNSIGNED_JWT" | rs_sign "${ALG#RS}" "$KEY" | b64enc) ;; |
| 38 |
ES*) SIGNATURE=$(echo -n "$UNSIGNED_JWT" | es_sign "${ALG#ES}" "$KEY" | b64enc) ;; |
| 39 |
esac |
| 40 |
|
| 41 |
echo "$UNSIGNED_JWT.$SIGNATURE" |