Last active
April 25, 2017 13:52
-
-
Save ggrandes/df7151b9e2fca02da93acf44bedf7b43 to your computer and use it in GitHub Desktop.
Base32 encoding/decoding RFC-3548
This file contains hidden or 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
| #!/usr/bin/perl -wT | |
| # https://gist.github.com/ggrandes/df7151b9e2fca02da93acf44bedf7b43 | |
| use strict; | |
| my $op = ($ARGV[0] || ""); | |
| my $text = ($ARGV[1] || ""); | |
| if (length($text) < 1) { | |
| print_usage(); | |
| } elsif (($op eq "-e") || ($op eq "--encode")) { | |
| print encode_rfc3548($text), "\n"; | |
| } elsif (($op eq "-d") || ($op eq "--decode")) { | |
| print decode_rfc3548($text), "\n"; | |
| } else { | |
| print_usage(); | |
| } | |
| sub print_usage { | |
| print "$0 <-e|-d> <input>", "\n"; | |
| exit 1; | |
| } | |
| sub encode_rfc3548 { | |
| my ($l, $e); | |
| $_ = unpack('B*', shift); | |
| s|(.....)|000$1|g; | |
| $l = length; | |
| if ($l & 7) { | |
| $e = substr($_, $l & ~7); | |
| $_ = substr($_, 0, $l & ~7); | |
| $_ .= ("000$e" . '0' x (5 - length $e)); | |
| } | |
| $_ = pack('B*', $_); | |
| tr|\0-\37|A-Z2-7|; | |
| $_; | |
| } | |
| sub decode_rfc3548 { | |
| my ($l); | |
| $_ = shift; | |
| tr|A-Z2-7|\0-\37|; | |
| $_ = unpack('B*', $_); | |
| s|000(.....)|$1|g; | |
| $l = length; | |
| $_ = substr($_, 0, $l & ~7) if ($l & 7); | |
| $_ = pack('B*', $_); | |
| $_; | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment