30

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.

Rusty Horse
  • 2,388
  • 7
  • 26
  • 38

4 Answers4

65

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)

plundra
  • 18,542
  • 3
  • 33
  • 27
9

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 
BeniBela
  • 16,412
  • 4
  • 45
  • 52
  • On CentOS8 you have to use `xxd -r -p -l 16`, joining the `-r -p` into `-rp` has the `-p` ignored and results in `xxd: sorry, cannot seek backwards.` – Hashbrown Jan 30 '22 at 05:19
1

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
mikentalk
  • 11
  • 1
0
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
Dennis Williamson
  • 346,391
  • 90
  • 374
  • 439