1
package security
2

3
import (
4
    "crypto/aes"
5
    "crypto/cipher"
6
    "crypto/rand"
7
    "encoding/base64"
8
    "errors"
9
    "io"
10
)
11

12
// Encrypt encrypts a byte-string `text` using a given `key`
13
func Encrypt(key, text []byte) (string, error) {
14 1
    block, err := aes.NewCipher(key)
15 1
    if err != nil {
16 0
        return "", err
17
    }
18 1
    b := base64.StdEncoding.EncodeToString(text)
19 1
    ciphertext := make([]byte, aes.BlockSize + len(b))
20 1
    iv := ciphertext[:aes.BlockSize]
21 1
    if _, err := io.ReadFull(rand.Reader, iv); err != nil {
22 0
        return "", err
23
    }
24 1
    cfb := cipher.NewCFBEncrypter(block, iv)
25 1
    cfb.XORKeyStream(ciphertext[aes.BlockSize:], []byte(b))
26 1
    return base64.StdEncoding.EncodeToString(ciphertext), nil
27
}
28

29
// Decrypt decrypts a byte-string `encodedText` using a given `key`
30
func Decrypt(key []byte, encodedText string) ([]byte, error) {
31 1
    text, _ := base64.StdEncoding.DecodeString(encodedText)
32 1
    block, err := aes.NewCipher(key)
33 1
    if err != nil {
34 0
        return nil, err
35
    }
36 1
    if len(text) < aes.BlockSize {
37 0
        return nil, errors.New("Ciphertext too short")
38
    }
39 1
    iv := text[:aes.BlockSize]
40 1
    text = text[aes.BlockSize:]
41 1
    cfb := cipher.NewCFBDecrypter(block, iv)
42 1
    cfb.XORKeyStream(text, text)
43 1
    data, err := base64.StdEncoding.DecodeString(string(text))
44 1
    if err != nil {
45 1
        return nil, err
46
    }
47 1
    return data, nil
48
}

Read our documentation on viewing source code .

Loading