Encoding to base32 from the shell

13,667

Solution 1

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.

Solution 2

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

$ which base32
/usr/bin/base32

Solution 3

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'

Solution 4

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
Share:
13,667

Related videos on Youtube

jdev
Author by

jdev

Hi there, I enjoy doing server-side programming and architecting high-performance infrastructure.

Updated on September 18, 2022

Comments

  • jdev
    jdev over 1 year

    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