Sobes.tech
Senior

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("All tests passed successfully") } }

sobes.tech AI

Answer from AI

In this code, you need to implement the RecoverPassword function, which restores the original password from an MD5 hash using a given alphabet alphabet. Since MD5 is a cryptographic hash function, there is no reverse transformation, but with a limited alphabet and password length, all options can be brute-forced.

Approach:

  • Generate all possible strings composed of characters from alphabet, starting from length 1 and increasing.
  • For each string, compute its MD5 and compare with the given hash.
  • If they match, return that string.

Example of brute-force implementation with a length limit (e.g., up to 7 characters):

func RecoverPassword(h []byte) string {
	maxLen := 7
	var dfs func(pos int, current []rune) string
	dfs = func(pos int, current []rune) string {
		if pos > 0 {
			if bytes.Equal(hashPassword(string(current)), h) {
				return string(current)
			}
		}
		if pos == maxLen {
			return ""
		}
		for _, c := range alphabet {
			res := dfs(pos+1, append(current, c))
			if res != "" {
				return res
			}
		}
		return ""
	}
	return dfs(0, []rune{})
}

Such brute-force will work, but as the password length increases, the time exponentially grows. For real-world tasks, this is not practical, but for educational purposes, it is suitable.