10
votes

I'm looking to encode an input string to base32 encoding directly from the shell. I'm looking to do this in ubuntu, but I imagine flavor doesn't particularly matter here.

Are there any existing linux/unix tools out there to simply do this?

Something along the lines of:

-bash-3.2$ echo -n 'hello' | base32

5 Answers 5

10
votes

Hmm, a quick package search doesn't give anything like a single, standalone utility.

On the other hand, it shows that there's an appropriate Perl library, and it's easy enough to whip up a quick perl script. Something like:

$ sudo apt-get install libmime-base32-perl

And then a script like base32enc.pl:

#!/usr/bin/perl

use MIME::Base32 qw( RFC );

undef $/;  # in case stdin has newlines
$string = <STDIN>;

$encoded = MIME::Base32::encode($string);

print "$encoded\n";

So:

$ echo -n "hello" | ./base32enc.pl
NBSWY3DP

The fairly sparse CPAN entry is: http://search.cpan.org/~danpeder/MIME-Base32-1.01/Base32.pm

So, a minor change will let you do decodes, also.

0
4
votes

It's installed by default in Ubuntu 16.04 as part of coreutils:

$ which base32
/usr/bin/base32
3
votes

Using Python:

$ python
Python 2.7.14 (default, Sep 27 2017, 12:15:00) 
[GCC 4.2.1 Compatible Apple LLVM 9.0.0 (clang-900.0.37)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> import base64
>>> base64.b32encode('hello')
'NBSWY3DP'
2
votes

Just an improvement of cjc excellent answer so we can have a base32 utility which works similarly to base64 in the way we can encode and decode:

#! /usr/bin/perl

use MIME::Base32;
use strict;

undef $/;

my $string = <STDIN>;
my $changed;

if ( $ARGV[0] eq "-d" ){
        $changed = MIME::Base32::decode($string);
}else{
        $changed = MIME::Base32::encode($string); 
}

if ( $changed =~ /\n$/ ) {
    printf $changed;
}else{
    printf $changed . "\n";
}

Test:

$ base32 < <(echo -n 'abcdef')
MFRGGZDFMY
$ base32 -d < <(echo  'MFRGGZDFMY')
abcdef
0
votes
  1. Install perl-MIME-Base32.noarch:

    yum install perl-MIME-Base32.noarch
    
  2. Save the script in bas32 filename:

    #!/usr/bin/perl
    
    use MIME::Base32 qw( RFC );
    
    undef $/;  # in case stdin has newlines
    $ed=$ARGV[0];
    $string=$ARGV[1];
    if ($ed eq "-e")
    {
    $encoded = MIME::Base32::encode($string);
    print "$encoded\n";
    }
    elsif ($ed eq "-d")
    {
    $decoded = MIME::Base32::decode($string);
    print "$decoded\n";
    }
    else { print " please pass option also\n";
    exit;
    }
    
    chmod +x base32
    cp base32 /usr/bin/
    base32 -e string
    base32 -d "any encoded value"
    

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .