-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathencoder.go
81 lines (63 loc) · 1.46 KB
/
encoder.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
package sender
import (
"crypto/aes"
"crypto/cipher"
"crypto/rand"
"io"
"io/ioutil"
"log"
"os"
)
const encodingStringLength = 32
func encode(password string, token string, file *os.File) {
password = normalizeEncodingString(password)
text := []byte(token)
key := []byte(password)
ci, err := aes.NewCipher(key)
checkErr(err)
gcm, err := cipher.NewGCM(ci)
checkErr(err)
nonce := make([]byte, gcm.NonceSize())
if _, err = io.ReadFull(rand.Reader, nonce); err != nil {
log.Fatal(err)
}
seal := gcm.Seal(nonce, nonce, text, nil)
_, err = file.Write(seal)
checkErr(err)
}
func decode(password string, file *os.File) string {
password = normalizeEncodingString(password)
key := []byte(password)
ci, err := aes.NewCipher(key)
checkErr(err)
gcm, err := cipher.NewGCM(ci)
checkErr(err)
data, err := ioutil.ReadAll(file)
checkErr(err)
size := gcm.NonceSize()
if size > len(data) {
log.Fatal("bad nonce size")
}
nonce, data := data[:size], data[size:]
token, err := gcm.Open(nil, nonce, data, nil)
if err != nil {
log.Fatal("token is invalid, please enter valid password or delete file")
}
return string(token)
}
func normalizeEncodingString(str string) string {
length := len(str)
if length < encodingStringLength {
strIndex := 0
for i := length; i < encodingStringLength; i++ {
str += string(str[strIndex])
if strIndex >= length {
strIndex = 0
} else {
strIndex++
}
}
return str
}
return str[:encodingStringLength]
}