-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathconstrain.go
78 lines (70 loc) · 1.56 KB
/
constrain.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
package main
import (
"strings"
"unicode"
)
func isNotAlNum(r rune) bool {
if unicode.IsLetter(r) {
return false
}
if unicode.IsDigit(r) {
return false
}
return true
}
func rotate(arr []string, amount byte) []string {
for i := byte(0); i < amount; i++ {
arr = append(arr, arr[0])
arr = arr[1:]
}
return arr
}
func between(min, interval, offset byte) byte {
return min + offset%interval
}
func constrain(hash string, size int, nonalnum bool) string {
hash = strings.TrimRight(hash, "=") // PwdHash uses "" for pad
start := size - 4
rv := hash[:start]
extras := strings.Split(hash[start:], "")
nextExtra := func() string {
if len(extras) > 0 {
rv := extras[0]
extras = extras[1:]
return rv
}
return ""
}
nextBetween := func(base int, interval byte) string {
return string([]byte{between(byte(base), interval, nextExtra()[0])})
}
if strings.IndexFunc(rv, unicode.IsUpper) >= 0 {
rv += nextExtra()
} else {
rv += nextBetween('A', 26)
}
if strings.IndexFunc(rv, unicode.IsLower) >= 0 {
rv += nextExtra()
} else {
rv += nextBetween('a', 26)
}
if strings.IndexFunc(rv, unicode.IsDigit) >= 0 {
rv += nextExtra()
} else {
rv += nextBetween('0', 10)
}
if nonalnum && strings.IndexFunc(rv, isNotAlNum) >= 0 {
rv += nextExtra()
} else {
rv += "+"
}
if !nonalnum {
for i := strings.IndexFunc(rv, isNotAlNum); i >= 0; i = strings.IndexFunc(rv, isNotAlNum) {
rv = rv[:i] + nextBetween('A', 26) + rv[i+1:]
}
}
list := strings.Split(rv, "")
list = rotate(list, nextExtra()[0])
rv = strings.Join(list, "")
return rv
}