-
Notifications
You must be signed in to change notification settings - Fork 4
/
autocert.go
93 lines (75 loc) · 1.98 KB
/
autocert.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 multiserverkit
import (
"context"
"crypto/aes"
"crypto/cipher"
"crypto/rand"
"errors"
"io"
"golang.org/x/crypto/acme/autocert"
)
type encryptedAutocertCache struct {
encryptionKey []byte
underlying autocert.Cache
}
func NewEncryptedAutocertCache(encryptionKey []byte, underlying autocert.Cache) autocert.Cache {
if len(encryptionKey) != 32 {
panic("encryptionkey must be exactly 32 bytes")
}
return &encryptedAutocertCache{
encryptionKey: encryptionKey,
underlying: underlying,
}
}
func (c *encryptedAutocertCache) Get(ctx context.Context, key string) ([]byte, error) {
// get value from underlying cache
v, err := c.underlying.Get(ctx, key)
if err != nil {
return nil, err
}
// decrypt value gotten from underlying cache
return decrypt(v, c.encryptionKey)
}
func (c *encryptedAutocertCache) Put(ctx context.Context, key string, data []byte) error {
// encrypt the value
encrypted, err := encrypt(data, c.encryptionKey)
if err != nil {
return err
}
// store the value in the underlying cache
return c.underlying.Put(ctx, key, encrypted)
}
func (c *encryptedAutocertCache) Delete(ctx context.Context, key string) error {
return c.underlying.Delete(ctx, key)
}
func encrypt(plaintext []byte, key []byte) ([]byte, error) {
c, err := aes.NewCipher(key)
if err != nil {
return nil, err
}
gcm, err := cipher.NewGCM(c)
if err != nil {
return nil, err
}
nonce := make([]byte, gcm.NonceSize())
if _, err = io.ReadFull(rand.Reader, nonce); err != nil {
return nil, err
}
return gcm.Seal(nonce, nonce, plaintext, nil), nil
}
func decrypt(ciphertext []byte, key []byte) ([]byte, error) {
c, err := aes.NewCipher(key)
if err != nil {
return nil, err
}
gcm, err := cipher.NewGCM(c)
if err != nil {
return nil, err
}
nonceSize := gcm.NonceSize()
if len(ciphertext) < nonceSize {
return nil, errors.New("ciphertext too short")
}
nonce, ciphertext := ciphertext[:nonceSize], ciphertext[nonceSize:]
return gcm.Open(nil, nonce, ciphertext, nil)
}