Sobes.tech
Senior

Tenemos una base de datos con contraseñas de usuarios, las contraseñas están hasheadadas (función hashPassword), y también se conoce el conjunto de caracteres que pueden ser utilizados en las contraseñas (variable alphabet). Nuestra tarea es implementar la función RecoverPassword para que recupere la contraseña a partir del hash conocido y TestRecoverPassword termine con éxito. Requisitos básicos: Cualquier método es válido 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() {

sobes.tech AI

Respuesta de la IA

Для восстановления пароля по известному MD5-хэшу и заданному алфавиту нужно перебрать все возможные комбинации символов из alphabet, вычислить их хэш и сравнить с заданным. При совпадении вернуть найденный пароль.

Пример реализации с перебором паролей длиной от 1 до некоторого максимума (например, 5):

package main

import (
    "crypto/md5"
    "fmt"
)

var alphabet = []rune{'a', 'b', 'c', 'd', '1', '2', '3'}

func hashPassword(in string) []byte {
    h := md5.Sum([]byte(in))
    return h[:]
}

func RecoverPassword(h []byte) string {
    maxLen := 5
    var attempt func(pos int, current []rune) string

    attempt = func(pos int, current []rune) string {
        if pos == 0 {
            // Проверяем текущую комбинацию
            candidate := string(current)
            if string(hashPassword(candidate)) == string(h) {
                return candidate
            }
            return ""
        }
        for _, ch := range alphabet {
            current[len(current)-pos] = ch
            res := attempt(pos-1, current)
            if res != "" {
                return res
            }
        }
        return ""
    }

    for length := 1; length <= maxLen; length++ {
        current := make([]rune, length)
        res := attempt(length, current)
        if res != "" {
            return res
        }
    }
    return ""
}

func main() {
    password := "abc1"
    h := hashPassword(password)
    recovered := RecoverPassword(h)
    fmt.Printf("Original: %s, Recovered: %s\n", password, recovered)
}

Этот код перебирает все возможные пароли длиной до 5 символов из заданного алфавита, вычисляет их MD5-хэш и сравнивает с заданным. При совпадении возвращает найденный пароль.

Обратите внимание, что такой перебор может быть очень затратным по времени при большом алфавите и длине пароля.