This repository has been archived by the owner on Jan 24, 2023. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 130
/
aes.go
93 lines (73 loc) · 2.25 KB
/
aes.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
81
82
83
84
85
86
87
88
89
90
91
92
93
package crypto
import (
"crypto/aes"
"crypto/cipher"
"crypto/rand"
"encoding/hex"
"errors"
"fmt"
"io"
"io/ioutil"
log "github.com/Sirupsen/logrus"
)
// Encrypt - Encrypt a token based on an encryption key
// The approach used here is based on the following direction on how to AES
// encrypt/decrypt our secret information, in this case tokens (normal, refresh
// and OAuth tokens).
// Source: https://github.com/giorgisio/examples/blob/master/aes-encrypt/main.go
func Encrypt(key, text []byte) (ciphertext []byte, err error) {
log.Debug("Encrypt")
var block cipher.Block
if block, err = aes.NewCipher(key); err != nil {
return nil, err
}
ciphertext = make([]byte, aes.BlockSize+len(string(text)))
// iv = initialization vector
iv := ciphertext[:aes.BlockSize]
if _, err = io.ReadFull(rand.Reader, iv); err != nil {
return
}
cfb := cipher.NewCFBEncrypter(block, iv)
cfb.XORKeyStream(ciphertext[aes.BlockSize:], text)
return
}
// Decrypt - Decrypt a token based on an encryption key
// The approach used here is based on the following direction on how to AES
// encrypt/decrypt our secret information, in this case tokens (normal, refresh
// and OAuth tokens).
// Source: https://github.com/giorgisio/examples/blob/master/aes-encrypt/main.go
func Decrypt(key, ciphertext []byte) (plaintext []byte, err error) {
log.Debug("Decrypt")
var block cipher.Block
if block, err = aes.NewCipher(key); err != nil {
return
}
if len(ciphertext) < aes.BlockSize {
err = errors.New("ciphertext too short")
return
}
iv := ciphertext[:aes.BlockSize]
ciphertext = ciphertext[aes.BlockSize:]
cfb := cipher.NewCFBDecrypter(block, iv)
cfb.XORKeyStream(ciphertext, ciphertext)
plaintext = ciphertext
return
}
// ReadEncryptionKey - Read the encryption key from the shared volume
func ReadEncryptionKey(v, f string) ([]byte, error) {
log.Debug("ReadEncryptionKey")
encryptionKey := fmt.Sprintf("/%s/%s", v, f)
if string(f[0]) == "/" {
encryptionKey = fmt.Sprintf("%s/%s", v, f)
}
key64chars, err := ioutil.ReadFile(encryptionKey)
if err != nil {
log.Errorf("Unable to read encryption key file: %+v\n", err)
return nil, err
}
key32bytes, err := hex.DecodeString(string(key64chars))
if err != nil {
fmt.Println(err)
}
return key32bytes, nil
}