forked from adt-automation/goRunner
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathcrypto.go
84 lines (75 loc) · 1.97 KB
/
crypto.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
package main
import (
"bytes"
"crypto/aes"
"crypto/cipher"
"encoding/binary"
"errors"
"fmt"
"log"
"strconv"
"strings"
"time"
)
func tsByteBuffer(timestamp int64) *bytes.Buffer {
buf := new(bytes.Buffer)
binary.Write(buf, binary.BigEndian, timestamp)
return buf
}
func buildIv(reqTime time.Time) []byte {
timestamp := reqTime.UnixNano() / (int64(time.Millisecond) / int64(time.Nanosecond))
buf := tsByteBuffer(timestamp)
iv := make([]byte, 0, 16)
iv = append(iv, buf.Bytes()[2:]...)
iv = append(iv, buf.Bytes()[2:]...)
iv = append(iv, buf.Bytes()[2:6]...)
return iv
}
func buildKey(keyStr string) []byte {
key := make([]byte, 0, 32)
if strings.Count(keyStr, ",") != 31 {
log.Fatal(fmt.Sprintf("32-byte key required, current key will be %d bytes", 1+strings.Count(keyStr, ",")))
}
for _, ds := range strings.Split(keyStr, ",") {
ds = strings.TrimSpace(ds)
di, err := strconv.Atoi(ds)
if err != nil {
log.Fatal(err.Error() + " during encryption key construction")
} else {
key = append(key, byte(di))
}
}
return key
}
func encrypt(key, iv, text []byte) (ciphertextOut []byte, err error) {
if len(text) < aes.BlockSize {
err = errors.New(fmt.Sprintf("input text is %d bytes, too short to encrypt", len(text)))
return
}
if len(text)%aes.BlockSize != 0 {
err = errors.New(fmt.Sprintf("input text is %d bytes, must be a multiple of %d", len(text), aes.BlockSize))
return
}
ciphertextOut = make([]byte, len(string(text)))
block, err := aes.NewCipher(key)
if err != nil {
return nil, err
}
cfb := cipher.NewCBCEncrypter(block, iv)
cfb.CryptBlocks(ciphertextOut, text)
return
}
func decrypt(key, iv, ciphertext []byte) (plaintextOut []byte, err error) {
plaintextOut = make([]byte, len(ciphertext))
block, err := aes.NewCipher(key)
if err != nil {
return
}
if len(ciphertext) < aes.BlockSize {
err = errors.New("ciphertext too short")
return
}
cfb := cipher.NewCBCDecrypter(block, iv)
cfb.CryptBlocks(plaintextOut, ciphertext)
return
}