简体   繁体   English

为什么PHP的md5与OpenSSL的md5不同?

[英]Why PHP's md5 is different from OpenSSL's md5?

I am quite confused as to why I am seeing different results for md5 hashing in PHP and in OpenSSL. 我对为什么在PHP和OpenSSL中看到md5哈希的结果不同感到非常困惑。

Here is the code that I am running: 这是我正在运行的代码:

php -r "echo md5('abc');"

Results in: 900150983cd24fb0d6963f7d28e17f72 结果为:900150983cd24fb0d6963f7d28e17f72

While this: 虽然这样:

echo abc | openssl md5

Results in: 0bee89b07a248e27c83fc3d5951213c1 结果在:0bee89b07a248e27c83fc3d5951213c1

Why? 为什么?

There is only one way to compute MD5. 只有一种方法可以计算MD5。

A blind guess is that the second one also includes a newline inside the string being hashed. 盲目的猜测是第二个在被散列的字符串内还包含换行符。

Yeh, verified it. 是的,验证了它。 That's it. 而已。

As everyone noted, the problem is that echo prints an extra newline. 众所周知,问题在于echo回显了额外的换行符。

However, the solution proposed ( echo -n ) is not completely correct. 但是,提出的解决方案( echo -n )并不完全正确。 According to the POSIX standard, " Implementations shall not support any options. " You'll make the world a bit better if you don't use it. 根据POSIX标准,“ 实现不支持任何选项。 ”如果不使用它,将会使世界变得更好。 Use 使用

printf %s abc | openssl md5

or simply 或简单地

printf abc | openssl md5

echo normally adds a new line character at the end of the string it outputs; echo通常在它输出的字符串的末尾添加一个换行符; that is the reason the MD5 values are different. 这就是MD5值不同的原因。

Try with echo -n abc | openssl md5 尝试使用echo -n abc | openssl md5 echo -n abc | openssl md5 . echo -n abc | openssl md5

As jdehaan notes, if you tell echo not output a newline, you get the answer you expect 正如jdehaan所指出的,如果您告诉echo不输出换行符,则会得到您期望的答案

echo -n "abc" | openssl md5
900150983cd24fb0d6963f7d28e17f72

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM