-
Notifications
You must be signed in to change notification settings - Fork 0
/
crypto.go
80 lines (68 loc) · 1.81 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
package v1
import (
"bytes"
"crypto/aes"
"crypto/cipher"
"crypto/rand"
"crypto/sha256"
"errors"
"io"
)
func AddPKCS7Padding(ciphertext []byte, blockSize int) []byte {
padding := blockSize - len(ciphertext)%blockSize
return append(ciphertext, bytes.Repeat([]byte{byte(padding)}, padding)...)
}
func RemovePKCS7Padding(origData []byte) []byte {
length := len(origData)
return origData[:(length - int(origData[length-1]))]
}
func (o Option) Encrypt(key []byte) Option {
block, err := aes.NewCipher(key)
if err != nil {
return Wrap(o.value, err)
}
blockSize := block.BlockSize()
src := AddPKCS7Padding(o.UnwrapBytes(), blockSize)
dst := make([]byte, blockSize+len(src))
iv := dst[:blockSize]
if _, err := io.ReadFull(rand.Reader, iv); err != nil {
return Wrap(o.value, err)
}
mode := cipher.NewCBCEncrypter(block, iv)
mode.CryptBlocks(dst[blockSize:], src)
return Option{
value: dst,
err: nil,
}
}
func (o Option) Decrypt(key []byte) Option {
block, err := aes.NewCipher(key)
if err != nil {
return Wrap(o.value, err)
}
src := o.UnwrapBytes()
srcCopy := make([]byte, len(src))
copy(srcCopy, src)
blockSize := block.BlockSize()
if len(srcCopy) < blockSize {
return Wrap(o.value, errors.New("ciphertext too short"))
}
iv := srcCopy[:blockSize]
srcCopy = srcCopy[blockSize:]
if len(srcCopy)%blockSize != 0 {
return Wrap(o.value, errors.New("ciphertext is not a multiple of the block size"))
}
mode := cipher.NewCBCDecrypter(block, iv)
// CryptBlocks can work in-place if the two arguments are the same.
mode.CryptBlocks(srcCopy, srcCopy)
return Option{
value: RemovePKCS7Padding(srcCopy),
err: nil,
}
}
func (o Option) Checksum() Option {
return Wrap(sha256.Sum256(o.UnwrapBytes()), nil)
}
func (o Option) Checksum224() Option {
return Wrap(sha256.Sum224(o.UnwrapBytes()), nil)
}