Created
February 2, 2022 13:18
-
-
Save fpawel/757574cd0ca04943bf6b528bb7c180f3 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package main | |
import ( | |
"bytes" | |
"crypto/md5" | |
"fmt" | |
"testing" | |
) | |
// There is a database with hashed user passwords (hashPassword function). | |
// There is also a known set of characters that can be used in passwords (variable alphabet). | |
// It is necessary to implement the RecoverPassword function so that it recovers the password using a known hash and TestRecoverPassword succeeds | |
var alphabet = "abcd123" | |
func recoverPass(h []byte, i int, s string) string { | |
if i == 0 { | |
if bytes.Equal(h, hashPassword(s)) { | |
return s | |
} | |
return "" | |
} | |
for _, c := range alphabet { | |
if s := recoverPass(h, i-1, s+string(c)); len(s) > 0 { | |
return s | |
} | |
} | |
return "" | |
} | |
func RecoverPassword(h []byte) string { | |
for i := 1; i <= 7; i++ { | |
s := recoverPass(h, i, "") | |
if len(s) > 0 { | |
return s | |
} | |
} | |
return "" | |
} | |
func TestRecoverPassword(t *testing.T) { | |
for _, exp := range []string{ | |
"a", | |
"12", | |
"abc333d", | |
} { | |
t.Run(exp, func(t *testing.T) { | |
act := RecoverPassword(hashPassword(exp)) | |
if act != exp { | |
t.Errorf("recovered: %q expected: %q", act, exp) | |
} | |
}) | |
} | |
} | |
func hashPassword(in string) []byte { | |
h := md5.Sum([]byte(in)) | |
return h[:] | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment