在Mac上使用bash
如何为字符串创建MD5哈希?我环境中没有md5sum
。我查了一下md5
的文档,但对它的作用感到困惑。
md5 "string"
不返回哈希值。
在Mac上使用bash
如何为字符串创建MD5哈希?我环境中没有md5sum
。我查了一下md5
的文档,但对它的作用感到困惑。
md5 "string"
不返回哈希值。
这应该可以正常工作 -
[jaypal:~/Temp] echo "this will be encrypted" | md5
72caf9daf910b5ef86796f74c20b7e0b
如果您更喜欢使用“Here String”表示法,则可以使用以下方法 -
[jaypal:~/Temp] md5 <<< 'this will be encrypted'
72caf9daf910b5ef86796f74c20b7e0b
根据man
页面,您可以尝试使用以下任何选项进行操作。
-s string
Print a checksum of the given string.
-p Echo stdin to stdout and append the checksum to stdout.
-q Quiet mode - only the checksum is printed out. Overrides the -r option.
[jaypal:~/Temp] md5 -s 'this will be encrypted'
MD5 ("this will be encrypted") = 502810f799de274ff7840a1549cd028a
[jaypal:~/Temp] md5 -qs 'this will be encrypted'
502810f799de274ff7840a1549cd028a
注意:MD5哈希始终产生相同的输出。你发现与上面示例不同的输出是由于评论中提到的一个原因。前两个示例使用尾随的换行符
字符来生成哈希。为了避免这种情况,你可以使用:
[jaypal:~/Temp] echo -n "this will be encrypted" | md5
502810f799de274ff7840a1549cd028a
例如,如果您使用echo -n "string" | md5
(注意-n
选项),则会得到b45cffe084dd3d20d928bee85e7b0f21
。但是,如果您使用echo "string" | md5
,则会得到b80fa55b1234f1935cea559d9efbc39a
。
或者,可以在shell中验证:
➜ [jaypal:~/Temp] [ $(echo "HOLA" | md5) = $(echo "HOLA" -n | md5) ]; echo "$?"
1
# 1 -> False. Hence, the result from echoing "HOLA" toggling the -n flag
# outputs different md5 checksums.
md5 -s string
输出: MD5("string") = b45cffe084dd3d20d928bee85e7b0f21
OSX使用md5
,但大多数Unix系统使用md5sum
。
这是rvm的rvmrc验证代码的一部分,它可以找到正确的md5二进制文件并进行包装。
__rvm_md5_for()
{
if builtin command -v md5 > /dev/null; then
echo "$1" | md5
elif builtin command -v md5sum > /dev/null ; then
echo "$1" | md5sum | awk '{print $1}'
else
rvm_error "Neither md5 nor md5sum were found in the PATH"
return 1
fi
return 0
}
(来自https://github.com/wayneeseguin/rvm/blob/master/scripts/functions/rvmrc 的代码)
正确的做法是使用echo -n string | md5
而不是echo "string" | md5
。(我正在使用zsh)
将echo -n string | md5
生成的md5哈希值转换回string
。
md5 -s string
也可以正常工作,这已经在这里指出了。
λ [~] → echo "string" | md5
b80fa55b1234f1935cea559d9efbc39a
λ [~] → echo -n string | md5
b45cffe084dd3d20d928bee85e7b0f21
λ [~] → md5 -s string
MD5 ("string") = b45cffe084dd3d20d928bee85e7b0f21
其他答案都是正确的。我也想提出openssl
:
➜ echo 'this will be hashed' | openssl md5
55be2dc2df2c1cc7bad72a0ecb338841
这相当于以下内容:
➜ echo 'this will be hashed' | openssl dgst -md5
# or
➜ openssl md5 <<< 'this will be hashed'
# or
➜ echo 'this will be hashed' | md5
从命令行开始:
md5 <<< "String to hash"
8a0a39505c5753ff64a0377ab0265509
md5 -s "String to hash"
给出的结果不同,因为默认情况下,bash 会在 here strings 的结尾添加换行符。 - gMalemd5 file.txt
输出:
MD5 (file.txt) = 91a7644643c884ee00737db24e478156
dd if=/dev/random count=20|md5
dd if=/dev/urandom count=16 bs=1 | md5
- ingyhere
502810f799de274ff7840a1549cd028a
,可以通过echo -n "this will be encrypted" | md5
获得。 - Managuecho -n
在某些平台上不太兼容--它会在要打印的字符串前面添加"-n"(然后也添加换行符)。为了更好的可移植性,请使用printf "%s" "this will be encrypted" | md5
。 - Gordon Davisson