How to Encode Strings to Base32 in Linux Shell: Command Line Methods & Examples


2 views

Base32 encoding converts binary data into ASCII characters using a 32-character subset (A-Z and 2-7), making it useful for:

  • Case-insensitive data transmission
  • Human-readable serialization
  • URL-safe encoding (unlike Base64)

Modern Linux distributions include these built-in methods:

# Using coreutils' base32 (available since GNU coreutils 8.22)
echo -n 'hello' | base32

Output: NBSWY3DP

# Decoding example
echo 'NBSWY3DP' | base32 --decode

Using Python

python3 -c "import base64; print(base64.b32encode('hello'.encode()).decode())"

Using OpenSSL

echo -n 'hello' | openssl base32

Using Perl

perl -MMIME::Base32 -e 'print MIME::Base32::encode("hello")'

Encoding Files

base32 < input_file.txt > encoded_output.txt

Generating OTP Secrets

head -c 16 /dev/urandom | base32

Base32 requires padding with = to make the length a multiple of 8. Some implementations handle this differently:

# To remove padding:
echo -n 'hello' | base32 | tr -d '='
# To ensure padding:
echo -n 'hello' | base32 | awk '{ mod = length % 8; if (mod != 0) { printf "%s", $0; for (i = 0; i < 8 - mod; i++) printf "="; print "" } else print }'

For large files (1GB test):

  • base32: ~12 sec
  • python: ~28 sec
  • openssl: ~15 sec

Base32 encoding converts binary data into a string of 32 characters (A-Z and 2-7), making it useful for case-insensitive systems and human-readable formats. Unlike Base64, it's more suitable for systems that don't handle mixed case well.

Most modern Linux distributions include base32 encoding/decoding tools:

# Using base32 command
echo -n 'hello' | base32

Sample output:

NBSWY3DP

If base32 isn't available, you can use these alternatives:

# Using openssl
echo -n 'hello' | openssl base32

# Using python
echo -n 'hello' | python -m base64 -e 32

# Using perl
echo -n 'hello' | perl -MMIME::Base32 -ne 'print MIME::Base32::encode($_);'

For file encoding:

# Encode a file
base32 input.txt > output.b32

# Decode a file
base32 -d output.b32 > original.txt

Combine with other shell commands:

# Encode SHA256 hash
sha256sum file.txt | cut -d' ' -f1 | xxd -r -p | base32

# Encode random data
head -c 32 /dev/urandom | base32

If you encounter problems:

  • Ensure you're using -n with echo to avoid newlines
  • Check for line wrapping with -w 0 parameter
  • Verify your system's base32 implementation supports RFC 4648