-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathencryption.go
51 lines (41 loc) · 944 Bytes
/
encryption.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
package main
import (
"bytes"
"crypto/aes"
"crypto/cipher"
"encoding/hex"
)
var aesCbcKey []byte
func setupCrypto(bikeKey string) {
key, err := hex.DecodeString(bikeKey)
if err != nil {
fatal(err.Error())
}
if len(key) != 16 {
fatal("bikeKey must be a 32 hex character string (16 bytes)")
}
aesCbcKey = key
}
func canDecrypt() bool {
return aesCbcKey != nil
}
func decrypt(ciphertext []byte) ([]byte, error) {
block, err := aes.NewCipher(aesCbcKey)
if err != nil {
return nil, err
}
const blockSize = 16
iv := [blockSize]byte{}
blockAlignment := len(ciphertext) % blockSize
if blockAlignment != 0 {
ciphertext = append(ciphertext, bytes.Repeat([]byte{0}, blockSize-blockAlignment)...)
}
cbc := cipher.NewCBCDecrypter(block, iv[:])
cbc.CryptBlocks(ciphertext, ciphertext)
for i := len(ciphertext) - 1; i >= 0; i-- {
if ciphertext[i] != 0 {
return ciphertext[:i+1], nil
}
}
return []byte{}, nil
}