-
Notifications
You must be signed in to change notification settings - Fork 0
/
util.go
68 lines (55 loc) · 1.6 KB
/
util.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
package smokering
import (
"bytes"
"crypto/cipher"
"crypto/rand"
"errors"
"fmt"
"io"
)
func pad(src []byte, size int) []byte {
padding := size - len(src)%size
padtext := bytes.Repeat([]byte{byte(padding)}, padding)
return append(src, padtext...)
}
func unpad(src []byte, size int) ([]byte, error) {
if len(src) == 0 {
return nil, errors.New("src must not be empty")
}
length := len(src)
if length%size != 0 {
return nil, fmt.Errorf("length %d not multiple of blocksize", length)
}
block := src[(length - size):]
padlen := block[size-1]
if padlen == 0 || int(padlen) > size {
return nil, errors.New("invalid padding")
}
unpadding := size - int(padlen)
if unpadding > length {
return nil, errors.New("invalid encryption key")
}
return src[:(length - size + unpadding)], nil
}
func encrypt(block cipher.Block, paddedtext []byte, blocksize int) (ciphertext []byte, err error) {
ciphertext = make([]byte, blocksize+len(paddedtext))
iv := ciphertext[:blocksize]
if _, err := io.ReadFull(rand.Reader, iv); err != nil {
return nil, err
}
mode := cipher.NewCBCEncrypter(block, iv)
mode.CryptBlocks(ciphertext[blocksize:], paddedtext)
return ciphertext, nil
}
func decrypt(block cipher.Block, ciphertext []byte, blocksize int) (paddedtext []byte, err error) {
if len(ciphertext) < blocksize {
return nil, errors.New("ciphertext too short")
}
iv := ciphertext[:blocksize]
if len(ciphertext)%blocksize != 0 {
return nil, errors.New("ciphertext is not a multiple of block size")
}
mode := cipher.NewCBCDecrypter(block, iv)
mode.CryptBlocks(ciphertext, ciphertext)
return ciphertext, nil
}