Encoding to base32 from the shell

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.


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'

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