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

我们两清 提交于 2019-12-04 07:35:29

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]

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.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!