Sobes.tech
Middle+

We have a database of user passwords, passwords are hashed (using hashPassword function), and we also know the set of characters that can be used in passwords (variable alphabet). Our task is to implement the RecoverPassword function so that it recovers the password from the known hash and TestRecoverPassword completes successfully. Basic requirements: Solve as you wish package main import ( "crypto/md5" "fmt" ) var alphabet = []rune{'a', 'b', 'c', 'd', '1', '2', '3'} func RecoverPassword(h []byte) string { return "" } func hashPassword(in string) []byte { h := md5.Sum([]byte(in)) return h[:] } func main() { tests := []string{"a", "12", "abc333d"} ok := true for _, exp := range tests { h := hashPassword(exp) act := RecoverPassword(h) if act != exp { fmt.Printf("Error: expected %q, got %q\n", exp, act) ok = false } } if ok { fmt.Println("Tests passed successfully") } }

sobes.tech AI

Answer from AI

Task — recover the original password from a known MD5 hash and alphabet. Since MD5 is a hash function, there is no reverse transformation, but you can try all possible combinations from alphabet and compare their hashes with the given one.

To pass the tests successfully, you need to implement a brute-force password search with length from 1 up to the maximum length of test passwords (for example, up to 7 characters).

An example solution with recursive brute-force:

func RecoverPassword(h []byte) string {
    var result string
    var found bool

    var dfs func(current []rune)
    dfs = func(current []rune) {
        if found {
            return
        }
        if len(current) > 0 {
            if stringHash := hashPassword(string(current)); stringHash != nil && stringEqual(stringHash, h) {
                result = string(current)
                found = true
                return
            }
        }
        if len(current) == 7 { // maximum length from tests
            return
        }
        for _, c := range alphabet {
            dfs(append(current, c))
        }
    }

    dfs([]rune{})
    return result
}

func stringEqual(a, b []byte) bool {
    if len(a) != len(b) {
        return false
    }
    for i := range a {
        if a[i] != b[i] {
            return false
        }
    }
    return true
}

This brute-force guarantees finding a password from the given alphabet and length up to 7 characters. In real conditions, brute-force can be expensive, but for testing and limited alphabet, it is suitable.