如何在 BASH 中将 md5 sum 编码为 base64

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/4583967/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-09 20:01:32  来源:igfitidea点击:

How to encode md5 sum into base64 in BASH

bashmd5base64

提问by Rusty Horse

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.

我需要将 md5 哈希编码为 base 64。问题是,如果将 md5sum 命令的输出提供给 base64 命令,它被视为文本而不是十六进制数据。如何管理?Base64 命令没有将其输入设置为十六进制数的选项。

Thanks for any help.

谢谢你的帮助。

回答by plundra

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

使用openssl dgst -md5 -binary代替md5sum。如果您愿意,您也可以使用它进行 base64 编码,以便所有用途仅使用一个程序。

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

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

(openssl md5instead of openssl dgst -md5works too, but I think it's better to be explicit)

openssl md5而不是也openssl dgst -md5有效,但我认为最好是明确的)

回答by BeniBela

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

在将十六进制传递给 base64 之前,您还可以使用 xxd(与 vim 一起提供)解码十六进制:

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

回答by Paused until further notice.

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

回答by mikentalk

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

在 busybox 中,您可能无法使用 for 循环语法。下面的 unhex() 是用 while 循环实现的:

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