哈希/ Unhash功能

时间:2018-03-14 19:38:51

标签: python function hash

我有以下代码。它是一个散列函数,可将单词转换为散列数:

def myHash (string):
    solution = 5
    alphabet = 'abcdegjkmnoprstuvwyz'

    for carac in string:
        solution = solution * 21 + alphabet.find(carac)
    return solution

test = 'mytest'
print (myHash(test))

我怎么做相反的方式?从哈希数字中我必须猜出字符串。

2 个答案:

答案 0 :(得分:0)

因为这看起来像是一个家庭作业,正如评论中所指出的那样,我将把代码写给你。

由于冲突,您无法反转此哈希函数。即,由于alphabet并非所有小写都存在,因此str.find会为 f h 等字符返回-1 i l q

因此,如果您收到哈希2204,则无法知道输入字符串是'af''ah''ai''al''aq'

虽然这是一种奇怪的行为而且几乎看似错误,所以让我们讨论一下alphabet = 'abcdefghijklmnopqrstuvwxyzsolution = solution * 26 + alphabet.find(carac)的情况。

然后alphabet中的尾随字符的索引为num % 26。然后,您可以通过减法和除法获得剩余字符的相应哈希值,并递归获取您的字符串。

答案 1 :(得分:-1)

我想你可以试试这个逻辑:

 '''
 Given all variable in your original code
 '''
 1. Define variable(Your String):  testF, Hashed ="", myHash(test)
 2. loop , stop condition (You figure it out):
       testF=alphabet[int(Hashed%(len(alphabet)+1))]+testF
       Hashed=int((Hashed-Hashed%(len(alphabet)+1))//(len(alphabet)+1))
相关问题