简体   繁体   中英

Hash decryption, what algorithm can I use

I have written hash calculate function:

var hash = function (string) {
  var h = 7;
  var i = 0;
  var letters = "acdegilmnoprstuw";

  while (i < string.length) {
    h = (h * 37 + letters.indexOf( string[i++] ));
  }

  return h;
};

Where string = "agdpeew" and result is 664804774844 . But now I don't know how I can decipher hash. So, If my input is 664804774844 , answer will agdpeew .

What algorithm can I use for this?

Maybe I can start with the division 664804774844 / 37 but how I can get letter indexes?

For short strings, you can start by expressing the number in base 37 - but why are you trying to do this? Most of the use cases for hash functions don't require you to invert the function, and many hash functions are designed for it to be difficult or impossible to invert the function, except by evaluating on input after input until you find one that produces the hash value you are looking for.

Below is the code written in Swift language, it has both encrypt & decrypt of the hash value

var letters = "acdegilmnoprstuw";

Hashing / Encrypt

func hash(s:String) -> Int{
    var h = 7 as Int;
    for (var i = 0; i < s.characters.count; i++) {
        // Getting the character at index 
        let s2: Character = s[s.startIndex.advancedBy(i)]; 
        // Getting index of string 'acdegilmnoprstuw'
        let l : Int = letters.startIndex.distanceTo(letters.characters.indexOf(s2)!);  
        h = (h * 37 + l);
    }
    return h;
}

Unhashing / Decrypt

func unhash(hashValue:Int) -> String{
    var h = hashValue
    var unhashedString : String = ""

    while(h > 37){
        unhashedString.append(letters[letters.startIndex.advancedBy(h % 37)])
        h = h / 37
    }
    return String(unhashedString.characters.reverse())
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM