base64.sh 728 B

12345678910111213141516171819202122232425262728293031
  1. #!/usr/bin/env bash
  2. set -euo pipefail
  3. _encode() {
  4. # - Print the input to stdout
  5. # - Remove the first two characters
  6. # - Convert from hex to binary
  7. # - Convert from binary to base64
  8. # - Remove newlines from `base64` output
  9. echo -n "$1" | cut -c 3- | xxd -r -p | base64 | tr -d \\n
  10. }
  11. encode() {
  12. # - Convert from base64 to hex
  13. # - Remove newlines from `xxd` output
  14. _encode "$1" | xxd -p | tr -d \\n
  15. }
  16. encodeURL() {
  17. # - Remove padding from `base64` output
  18. # - Replace `+` with `-`
  19. # - Replace `/` with `_`
  20. # - Convert from base64 to hex
  21. # - Remove newlines from `xxd` output
  22. _encode "$1" | sed 's/=//g' | sed 's/+/-/g' | sed 's/\//_/g' | xxd -p | tr -d \\n
  23. }
  24. # $1: function name
  25. # $2: input
  26. $1 $2