-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.go
106 lines (92 loc) · 1.98 KB
/
main.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
package main
import (
"crypto/md5"
"fmt"
)
const maxPasswordLength = 5
var chars = []string{"a", "b", "c", "d", "e", "f", "g"}
func BruteForcePassword(hash []byte) string {
return bruteForceLinearReusingSpace(hash)
}
func bruteForceRecursively(hash []byte, passwd string) string {
if compareHash(hash, getMD5Hash(passwd)) {
return passwd
}
for i := 0; i < len(chars); i++ {
if len(passwd) == maxPasswordLength {
return ""
}
if str := bruteForceRecursively(hash, passwd+chars[i]); str != "" {
return str
}
}
return ""
}
func bruteForceLinear(hash []byte) string {
stack := []string{""}
for len(stack) > 0 {
length := len(stack)
for _, passwd := range stack {
if compareHash(hash, getMD5Hash(passwd)) {
return passwd
}
if len(passwd) < maxPasswordLength {
for i := 0; i < len(chars); i++ {
stack = append(stack, passwd+chars[i])
}
}
}
stack = stack[length:]
}
return ""
}
func bruteForceLinearReusingSpace(hash []byte) string {
buff := make([]byte, maxPasswordLength)
state := make([]int, maxPasswordLength)
var pos int
for pos != -1 {
if pos == maxPasswordLength {
pos--
continue
}
if state[pos] == len(chars)-1 {
state[pos] = 0
pos--
continue
}
buff[pos] = chars[state[pos]][0]
state[pos]++
pos++
if compareHash(hash, getMD5Hash(string(buff[:pos]))) {
return string(buff[:pos])
}
}
return ""
}
func getMD5Hash(text string) []byte {
hasher := md5.New()
hasher.Write([]byte(text))
return hasher.Sum(nil)
}
func compareHash(a, b []byte) bool {
if len(a) != len(b) {
return false
}
for i := range a {
if a[i] != b[i] {
return false
}
}
return true
}
func main() {
passwords := []string{"a", "b", "c"}
for i := 0; i < len(passwords); i++ {
hash := getMD5Hash(passwords[i])
if passwd := BruteForcePassword(hash); passwd == passwords[i] {
fmt.Printf("Find password: %s - %s\n", passwords[i], passwd)
} else {
fmt.Printf("Loss: want %s, got %s\n", passwords[i], passwd)
}
}
}