在Mathematica中作为字符串给出的数据的加密散列(sha1或md5) [英] Cryptographic hash (sha1 or md5) of data given as a string in Mathematica

查看:403
本文介绍了在Mathematica中作为字符串给出的数据的加密散列(sha1或md5)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

abc的sha1哈希是

The sha1 hash of "abc" is

a9993e364706816aba3e25717850c26c9cd0d89d

使用 Hash 函数获取Mathematica告诉你的唯一方法是

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

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

(IntegerString的东西只是像大多数实现一样以十六进制输出。)

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

请注意

Hash["abc", "SHA"]

给出\abc\的哈希值 - 不是你想要的!事实上,我们可以得到abc的正确散列的唯一原因是因为符号 abc 的Mathematica表示恰好是字符串abc 。
对于绝大多数字符串,这不是这样的。

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.

那么如何获取Mathematica中任意字符串的哈希值呢?

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

推荐答案

使用 StringToStream 可以减少kludgily, c $ c> FileHash 可以将输入流作为参数。然后您的 sha1 函数变成:

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]

这篇关于在Mathematica中作为字符串给出的数据的加密散列(sha1或md5)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆