Debian Codegraph @

pkg/crypto/crypto.go

raw
1 package crypto
2
3 import (
4 "crypto/aes"
5 "crypto/cipher"
6 "crypto/rand"
7 "encoding/base64"
8 "errors"
9 "io"
10 )
11
12 var ErrCipherTextBlockSize = errors.New("ciphertext block size is too short")
13
14 func EncryptAES(data string, key string) (string, error) {
15 encrypted, err := EncryptBytesAES([]byte(data), key)
16 if err != nil {
17 return "", err
18 }
19
20 return base64.RawURLEncoding.EncodeToString(encrypted), nil
21 }
22
23 func EncryptBytesAES(plainText []byte, key string) ([]byte, error) {
24 block, err := aes.NewCipher([]byte(key))
25 if err != nil {
26 return nil, err
27 }
28
29 cipherText := make([]byte, aes.BlockSize+len(plainText))
30 iv := cipherText[:aes.BlockSize]
31 if _, err = io.ReadFull(rand.Reader, iv); err != nil {
32 return nil, err
33 }
34
35 stream := cipher.NewCFBEncrypter(block, iv)
36 stream.XORKeyStream(cipherText[aes.BlockSize:], plainText)
37
38 return cipherText, nil
39 }
40
41 func DecryptAES(data string, key string) (string, error) {
42 text, err := base64.RawURLEncoding.DecodeString(data)
43 if err != nil {
44 return "", err
45 }
46 decrypted, err := DecryptBytesAES(text, key)
47 if err != nil {
48 return "", err
49 }
50 return string(decrypted), nil
51 }
52
53 func DecryptBytesAES(cipherText []byte, key string) ([]byte, error) {
54 block, err := aes.NewCipher([]byte(key))
55 if err != nil {
56 return nil, err
57 }
58
59 if len(cipherText) < aes.BlockSize {
60 return nil, ErrCipherTextBlockSize
61 }
62 iv := cipherText[:aes.BlockSize]
63 cipherText = cipherText[aes.BlockSize:]
64
65 stream := cipher.NewCFBDecrypter(block, iv)
66 stream.XORKeyStream(cipherText, cipherText)
67
68 return cipherText, err
69 }