Rusty Horse
Rusty Horse

Reputation: 2428

How to encode md5 sum into base64 in BASH

I need to encode md5 hash to base 64. The problem is that if give output of md5sum command to base64 command, it is considered as a text and not as a hexadecimal data. How to manage it? Base64 command has no option to set it's input as a hexadecimal number.

Thanks for any help.

Upvotes: 30

Views: 32550

Answers (4)

plundra
plundra

Reputation: 19252

Use openssl dgst -md5 -binary instead of md5sum. If you want, you can use it to base64-encode as well, to only use one program for all uses.

echo -n foo | openssl dgst -md5 -binary | openssl enc -base64

(openssl md5 instead of openssl dgst -md5 works too, but I think it's better to be explicit)

Upvotes: 65

BeniBela
BeniBela

Reputation: 16927

You can also use xxd (comes with vim) to decode the hex, before passing it to base64:

(echo 0:; echo -n foo | md5sum) | xxd -rp -l 16 | base64 

Upvotes: 9

mikentalk
mikentalk

Reputation: 11

In busybox you might not be able to use for loop syntax. Below unhex() is implemented with a while loop instead:

unhex ()
{
    b=0;
    while [ $b -lt ${#1} ];
    do
        printf "\\x${1:$b:2}";
        b=$((b += 2));
    done
}

md5sum2bytes ()
{
    while read -r md5sum file; do
        unhex $md5sum;
    done
}

md5sum inputfile | md5sum2bytes | base64

Upvotes: 1

Dennis Williamson
Dennis Williamson

Reputation: 360575

unhex ()
{
    for ((b=0; b<${#1}; b+=2))
    do
        printf "\\x${1:$b:2}";
    done
}

md5sum2bytes ()
{
    while read -r md5sum file; do
        unhex $md5sum;
    done
}

md5sum inputfile | md5sum2bytes | base64

Upvotes: 0

Related Questions