-
Notifications
You must be signed in to change notification settings - Fork 4
/
Copy pathtripcode.go
96 lines (83 loc) · 2.3 KB
/
tripcode.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
/*
Package tripcode generates 4chan compatible tripcodes mainly for anonymous forums.
There are different implementations of the tripcode algorithm. This one is based on code
from http://avimedia.livejournal.com/1583.html
Example usage:
package main
import "github.com/aquilax/tripcode"
func main() {
print(tripcode.Tripcode("password")
print(tripcode.SecureTripcode("password", "secure salt"))
}
*/
package tripcode
import (
"bytes"
"crypto/sha1"
"encoding/base64"
"strings"
"gitlab.com/nyarla/go-crypt"
"golang.org/x/text/encoding/japanese"
"golang.org/x/text/transform"
)
const saltTable = "" +
"................................" +
".............../0123456789ABCDEF" +
"GABCDEFGHIJKLMNOPQRSTUVWXYZabcde" +
"fabcdefghijklmnopqrstuvwxyz....." +
"................................" +
"................................" +
"................................" +
"................................"
func convert(text string) string {
var s bytes.Buffer
transform.NewWriter(&s, japanese.ShiftJIS.NewEncoder()).Write([]byte(text))
return s.String()
}
func htmlEscape(text string) string {
r := strings.NewReplacer(
"&", "&",
"\"", """,
"<", "<",
">", ">",
)
return r.Replace(text)
}
func generateSalt(password string) string {
var salt [2]rune
pass := []rune(password + "H.")[1:3]
for i, r := range pass {
salt[i] = rune(saltTable[r%256])
}
return string(salt[:])
}
func prepare(password string) string {
password = convert(password)
password = htmlEscape(password)
if len(password) > 8 {
password = password[:8]
}
return password
}
// Tripcode generates a tripcode for the provided password.
func Tripcode(password string) string {
password = prepare(password)
if password == "" {
return password
}
salt := generateSalt(password)
code := crypt.Crypt(password, salt)
l := len(code)
return code[l-10 : l]
}
// SecureTripcode generates a secure tripcode based
// on the provided password and a secure salt combination.
func SecureTripcode(password string, secureSalt string) string {
password = prepare(password)
// Append password+salt and calculate sha1 hash.
hash := sha1.New().Sum(append([]byte(password), []byte(secureSalt)...))
salt := base64.StdEncoding.EncodeToString(hash)
code := crypt.Crypt(password, "_..A."+salt[:4])
l := len(code)
return code[l-10 : l]
}