Cryptographic hash (sha1 or md5) of data given as

2019-04-09 04:58发布

The sha1 hash of "abc" is

a9993e364706816aba3e25717850c26c9cd0d89d

The only way to get Mathematica to tell you that with its Hash function is

Hash[abc, "SHA"]   // IntegerString[#, 16]&

(The IntegerString thing is just to output it in hex like most implementations do.)

Note that

Hash["abc", "SHA"]

gives the hash of "\"abc\"" -- not what you want! In fact, the only reason we could get the correct hash of "abc" was because the Mathematica representation of the symbol abc happens to be the string "abc". For the vast majority of strings, this will not be the case.

So how do you take the hash of an arbitrary string in Mathematica?

2条回答
Bombasti
2楼-- · 2019-04-09 05:28

You can do it less kludgily by using StringToStream and the fact that FileHash can take an input stream as an argument. Then your sha1 function becomes:

sha1[s_String] := Module[{stream = StringToStream[s], hash},
  hash = FileHash[stream,"SHA"];
  Close[stream];
  hash]
查看更多
倾城 Initia
3楼-- · 2019-04-09 05:36

Here's a kludge that works. Write the string to a temp file and use FileHash:

sha1[s_String] := Module[{stream, file, hash},
  stream = OpenWrite[];
  WriteString[stream, s];
  file = Close[stream];
  hash = FileHash[file, "SHA"];
  DeleteFile[file];
  hash]

You might also want to define

hex = IntegerString[#, 16]&;

and return hex@hash in the above function.

查看更多
登录 后发表回答