【发布时间】:2012-02-18 06:56:30
【问题描述】:
如何在 Mac 上使用 bash 为字符串创建 md5 哈希? md5sum 在我的环境中不存在。我为 md5 做了一个man,但我对它的真正作用感到困惑。
md5 "string"
不返回哈希值。
【问题讨论】:
标签: macos bash cryptography
如何在 Mac 上使用 bash 为字符串创建 md5 哈希? md5sum 在我的环境中不存在。我为 md5 做了一个man,但我对它的真正作用感到困惑。
md5 "string"
不返回哈希值。
【问题讨论】:
标签: macos bash cryptography
这应该可行 -
[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 总是产生相同的哈希值。您发现输出与上面给出的示例不同的原因是由于在 cmets 中提出的一点。前两个示例使用结尾的 newline 字符来生成散列。为避免这种情况,您可以使用:
[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.
【讨论】:
this will be *hashed*,加密表示双向 ;)
502810f799de274ff7840a1549cd028a,可以通过echo -n "this will be encrypted" | md5获取。
echo -n 不是很便携——在某些平台上,它会在要打印的字符串前面添加“-n”(然后也添加换行符)。使用printf "%s" "this will be encrypted" | md5 以获得更好的可移植性。
OSX 使用 md5,但大多数 unice 使用 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的代码)
【讨论】:
您可能希望在这里使用一些随机性,否则密码将始终相同。这应该有效:
dd if=/dev/random count=20|md5
【讨论】:
实现你的要求:
md5 -s string
输出:MD5(“字符串”)= b45cffe084dd3d20d928bee85e7b0f21
【讨论】:
从命令行:
md5 <<< "String to hash"
8a0a39505c5753ff64a0377ab0265509
【讨论】:
md5 -s "String to hash" 不同的结果,因为默认情况下,bash 在here strings 末尾添加换行符
正确的做法是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
【讨论】: