Skip to content

Instantly share code, notes, and snippets.

@briandfoy
Last active April 27, 2022 18:18
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save briandfoy/7c8cbd912a3b1d095ef0b6b245968b7d to your computer and use it in GitHub Desktop.
Save briandfoy/7c8cbd912a3b1d095ef0b6b245968b7d to your computer and use it in GitHub Desktop.
A Unicode-safe HTTP basic auth string encoder/decoder
#!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 bdfoy@cpan.org fake_password
YmRmb3lAY3Bhbi5vcmc6ZmFrZV9wYXNzd29yZA==
$ basic_auth YmRmb3lAY3Bhbi5vcmc6ZmFrZV9wYXNzd29yZA==
bdfoy@cpan.org
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<bdfoy@cpan.org>
=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