Cryptographic hash (sha1 or md5) of data given as a string in Mathematica

Hash sha1 from "abc"

a9993e364706816aba3e25717850c26c9cd0d89d

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

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

(An IntegerString is just its output in hexadecimal, as most implementations do.)

note that

Hash["abc", "SHA"]

gives the hash "\" abc \ "" - not what you want! In fact, the only reason we could get the correct "abc" hash was because the Mathematica representation of the character abcis the string "abc". For the vast majority of lines, this is not so.

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

+5
2

, StringToStream , FileHash . sha1 :

sha1[s_String] := Module[{stream = StringToStream[s], hash},
  hash = FileHash[stream,"SHA"];
  Close[stream];
  hash]
+6

. temp FileHash:

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

hex = IntegerString[#, 16]&;

hex@hash .

+2

All Articles