-
Notifications
You must be signed in to change notification settings - Fork 0
/
crypt.go
56 lines (46 loc) · 1.12 KB
/
crypt.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
package main
import (
"bytes"
"crypto/cipher"
"crypto/rand"
"encoding/base64"
"errors"
"io"
)
func addPadding(blockSize int, d []byte) []byte {
padding := make([]byte, blockSize-len(d)%blockSize)
return append(d, padding...)
}
func encrypt(block cipher.Block, text []byte) ([]byte, error) {
bs := block.BlockSize()
text = addPadding(bs, text)
res := make([]byte, bs+len(text))
iv := res[:bs]
if _, err := io.ReadFull(rand.Reader, iv); err != nil {
return nil, err
}
m := cipher.NewCBCEncrypter(block, iv)
m.CryptBlocks(text, text)
copy(res[bs:], text)
return res, nil
}
func decrypt(block cipher.Block, text []byte) ([]byte, error) {
bs := block.BlockSize()
if len(text) < bs {
return nil, errors.New("cipher text too short")
}
iv := text[:bs]
text = text[bs:]
m := cipher.NewCBCDecrypter(block, iv)
m.CryptBlocks(text, text)
text = bytes.TrimRight(text, "\x00")
return text, nil
}
func decryptURLBase64(block cipher.Block, input string) ([]byte, error) {
text, err := base64.URLEncoding.DecodeString(input)
if err != nil {
return nil, err
}
text, err = decrypt(block, text)
return text, err
}