Created
October 17, 2019 09:45
-
-
Save alvis/89007e96f7958f2686036d4276d28e47 to your computer and use it in GitHub Desktop.
bash: base64url encode and decode
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# base64url encode | |
function base64url_encode { | |
(if [ -z "$1" ]; then cat -; else echo -n "$1"; fi) | | |
openssl base64 -e -A | | |
sed s/\\+/-/g | | |
sed s/\\//_/g | | |
sed -E s/=+$// | |
} | |
# base64url decode | |
function base64url_decode { | |
INPUT=$(if [ -z "$1" ]; then echo -n $(cat -); else echo -n "$1"; fi) | |
MOD=$(($(echo -n "$INPUT" | wc -c) % 4)) | |
PADDING=$(if [ $MOD -eq 2 ]; then echo -n '=='; elif [ $MOD -eq 3 ]; then echo -n '=' ; fi) | |
echo -n "$INPUT$PADDING" | | |
sed s/-/+/g | | |
sed s/_/\\//g | | |
openssl base64 -d -A | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
can you help me please
[email protected]