问题描述
在此测试MD5的Javascript实现: 给出以下输出:
Testing the Javascript Implementation of MD5 here: http://www.webtoolkit.info/javascript-md5.html gives the following output:
MD5("muzaaya") = "00e081abefbbbf72b2d5258196a9b6d0"
去我的erlang shell,并计算相同值的MD5,我得到这个:
Going to my erlang shell, and calculating the MD5 of the same value i get this:
Eshell V5.8.4 (abort with ^G)
1> erlang:md5("muzaaya").
<<0,224,129,171,239,187,191,114,178,213,37,129,150,169,
182,208>>
2>
我如何比较两个?如果JavaScript前端应用程序的MD5结果来到我的Erlang后端,我想要比较两个Digest。我如何将Javascript MD5摘要与Erlang的摘要相匹配?
How can i compare the two? If the MD5 result from the JavaScript front end app comes to my Erlang backend, i would like to be able to compare the two Digests. How can i match the Javascript MD5 digest to that of Erlang?
推荐答案
MD5哈希本质上是一个128位的数字。
And MD5 hash is in essence a 128-bit number.
您将Erlang中的MD5值作为16个字符(16 * 8 = 128)的二进制格式收到。该二进制文件中的每个数字都必须转换为十六进制,以与JavaScript的MD5输出(这是一个十六进制字符串)相当:
You receive the MD5 value in Erlang as a binary of 16 characters (16 * 8 = 128). Each number in that binary has to be converted into hexadecimal to be comparable to JavaScript's MD5 output (which is a hexadecimal string):
2> lists:flatten([io_lib:format("~2.16.0b", [B]) || <<B>> <= MD5]).
"00e081abefbbbf72b2d5258196a9b6d0"
首先,我们从二进制文件中取出每个字节,并使用 io_lib
模块将其格式化为十六进制字符串。然后,我们使用flatten函数将其显示为可读字符串(尽管如果要将值写入文件或套接字,这是不必要的,因为它们能够处理深io列表,嵌套的字符列表或二进制文件)
First, we take each byte from the binary and use the io_lib
module to format it to a hexadecimal string. Then we use the flatten function to display it as a readable string (although this isn't necessary if you're going to write the value to a file or a socket since they are able to handle deep io lists, nested lists of characters or binaries).
使用的格式字符串〜2.16.0b
表示格式化整数( b
)使用基础 16
和填充宽度 2
与填充字符 0
。
The format string used, ~2.16.0b
means format an integer (b
) using base 16
and padding to width 2
with the padding character 0
.
如果你想要一个二进制文件,你可以使用以下二进制理解:
If you want a binary, you could use the following binary comprehension:
3> << << (list_to_binary(io_lib:format("~2.16.0b", [C])))/binary >>
|| <<C>> <= MD5 >>.
<<"00e081abefbbbf72b2d5258196a9b6d0">>
(而不是 io_lib:format / 2
还有 http_util:integer_to_hexlist / 1
,虽然我不知道它是否更快)
(Instead of io_lib:format/2
there is also http_util:integer_to_hexlist/1
, although I don't know if it is faster)
这篇关于Erlang和JavaScript MD5 Digest匹配的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!