Last active
April 27, 2022 18:18
-
-
Save briandfoy/7c8cbd912a3b1d095ef0b6b245968b7d to your computer and use it in GitHub Desktop.
A Unicode-safe HTTP basic auth string encoder/decoder
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
#!perl | |
use v5.10; | |
use utf8; | |
use Encode; | |
use I18N::Langinfo qw(langinfo CODESET); | |
use MIME::Base64; | |
my $codeset = langinfo(CODESET); | |
say do { | |
if( @ARGV == 1 ) { # decode | |
join "\n", | |
map { Encode::decode($codeset, $_, Encode::FB_CROAK) } | |
split /:/, MIME::Base64::decode( $ARGV[0] ), 2; | |
} | |
elsif( @ARGV == 2 ) { # encode | |
my( $user, $pass ) = map { Encode::encode($codeset, $_, Encode::FB_CROAK) } @ARGV; | |
MIME::Base64::encode( join ':', $user, $pass ) =~ s/\s*\z//r | |
} | |
else { | |
print <<~'HERE'; | |
Usage: | |
$ basic_auth username password | |
dXNlcm5hbWU6cGFzc3dvcmQ= | |
$ basic_auth dXNlcm5hbWU6cGFzc3dvcmQ= | |
username | |
password | |
HERE | |
exit(2) | |
} | |
}; | |
=encoding utf8 | |
=head1 NAME | |
basic_auth - encode or decode basic auth strings | |
=head1 SYNOPSIS | |
$ basic_auth [email protected] fake_password | |
YmRmb3lAY3Bhbi5vcmc6ZmFrZV9wYXNzd29yZA== | |
$ basic_auth YmRmb3lAY3Bhbi5vcmc6ZmFrZV9wYXNzd29yZA== | |
[email protected] | |
fake_password | |
This is Unicode-safe: | |
$ basic_auth bdfoy⁰@cpan.org fake_password | xargs basic_auth | |
bdfoy⁰@cpan.org | |
fake_password | |
=head1 DESCRIPTION | |
The task to creating the value for HTTP basic auth seems simple, but | |
it's slightly complicated because you need to encode/decode the octets. | |
=head1 AUTHOR | |
brian d foy, C<[email protected]> | |
=head1 LICENSE | |
This code is under the Artistic License 2.0. | |
=cut |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment