开发者

How to encode md5 sum into base64 in BASH

开发者 https://www.devze.com 2023-02-02 08:54 出处:网络
开发者_如何学JAVAI 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 i
开发者_如何学JAVA

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.


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)


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 


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


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
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号