/
cipher.go
70 lines (56 loc) · 1.49 KB
/
cipher.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
package clickbank
import (
"crypto/aes"
"crypto/cipher"
"errors"
"strings"
)
type CryptStruct struct {
key []byte
iv []byte
cipher cipher.Block
}
var ErrInvalidInput = errors.New("input is not a factor of the cipher's blocksize")
var ErrInvalidPadding = errors.New("decrypted output does not appear to be correctly PKCS5 padded")
/* Create a new CrypteStruct */
func NewCryptStruct(key []byte, iv []byte) (*CryptStruct, error) {
cipher, err := aes.NewCipher(key)
if err != nil {
return nil, err
}
return &CryptStruct{key, iv[:cipher.BlockSize()], cipher}, nil
}
/* Decrypt Something */
func (c *CryptStruct) Decrypt(input []byte) ([]byte, error) {
ctx := cipher.NewCBCDecrypter(c.cipher, c.iv)
// Ensure that the input meets the correct blocksize
if len(input)%c.cipher.BlockSize() != 0 {
return nil, ErrInvalidInput
}
ctx.CryptBlocks(input, input)
return input, nil
}
func (c *CryptStruct) DecryptPKCS5(input []byte) ([]byte, error) {
r, err := c.Decrypt(input)
if err != nil {
return nil, err
}
return PKCS5Unpad(r)
}
func PKCS5Unpad(input []byte) ([]byte, error) {
// Expect the last byte of the string to have the length of padding
length := len(input)
padding_size := int(input[length-1])
if len(input) < padding_size {
return nil, ErrInvalidPadding
}
return input[:length-padding_size], nil
}
func StripCtrlChars(input []byte) string {
return strings.TrimFunc(string(input), func(r rune) bool {
if r <= 32 && r == 127 {
return true
}
return false
})
}