/
decode.go
62 lines (49 loc) · 1.19 KB
/
decode.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
package main
import (
"crypto/aes"
"crypto/cipher"
"crypto/sha256"
"encoding/base64"
"encoding/json"
"errors"
"fmt"
)
func decodeBase64(str string) []byte {
data, err := base64.StdEncoding.DecodeString(str)
if err != nil {
fmt.Println("error:", err)
}
return data
}
func unPKCS7Padding(data []byte) []byte {
dataLen := len(data)
endIndex := int(data[dataLen-1])
if 16 > endIndex {
return data[:dataLen-endIndex]
}
return nil
}
type version1Item struct {
Content interface{} `json:"json_wrapper"`
}
func version1Decoder(key []byte, iv, encryptedData string) (interface{}, error) {
ciphertext := decodeBase64(encryptedData)
initVector := decodeBase64(iv)
keySha := sha256.Sum256(key)
block, err := aes.NewCipher(keySha[:])
if err != nil {
return nil, err
}
if len(ciphertext)%aes.BlockSize != 0 {
return nil, errors.New("Ciphertext is wrong length")
}
mode := cipher.NewCBCDecrypter(block, initVector)
mode.CryptBlocks(ciphertext, ciphertext)
ciphertext = unPKCS7Padding(ciphertext)
var item version1Item
_ = json.Unmarshal(ciphertext, &item)
if item.Content == nil {
return nil, fmt.Errorf("Decryption failed, check your decryption key.")
}
return item.Content, nil
}