|
| 1 | +package certcache |
| 2 | + |
| 3 | +import ( |
| 4 | + "context" |
| 5 | + "crypto/cipher" |
| 6 | + cryptorand "crypto/rand" |
| 7 | + "errors" |
| 8 | + |
| 9 | + "golang.org/x/crypto/acme/autocert" |
| 10 | + "golang.org/x/crypto/chacha20poly1305" |
| 11 | +) |
| 12 | + |
| 13 | +type EncryptedCache struct { |
| 14 | + aead cipher.AEAD |
| 15 | + next autocert.Cache |
| 16 | +} |
| 17 | + |
| 18 | +func NewEncryptedCache(key []byte, next autocert.Cache) (*EncryptedCache, error) { |
| 19 | + aead, err := chacha20poly1305.NewX(key) |
| 20 | + if err != nil { |
| 21 | + return nil, err |
| 22 | + } |
| 23 | + return &EncryptedCache{ |
| 24 | + aead: aead, |
| 25 | + next: next, |
| 26 | + }, nil |
| 27 | +} |
| 28 | + |
| 29 | +func (c *EncryptedCache) Get(ctx context.Context, key string) ([]byte, error) { |
| 30 | + encryptedData, err := c.next.Get(ctx, key) |
| 31 | + if err != nil { |
| 32 | + return nil, err |
| 33 | + } |
| 34 | + |
| 35 | + if len(encryptedData) < c.aead.NonceSize() { |
| 36 | + return nil, errors.New("ciphertext too short") |
| 37 | + } |
| 38 | + |
| 39 | + // Split nonce and ciphertext. |
| 40 | + nonce, ciphertext := encryptedData[:c.aead.NonceSize()], encryptedData[c.aead.NonceSize():] |
| 41 | + |
| 42 | + // Decrypt the data and check it wasn't tampered with. |
| 43 | + plaintext, err := c.aead.Open(nil, nonce, ciphertext, []byte(key)) |
| 44 | + if err != nil { |
| 45 | + return nil, err |
| 46 | + } |
| 47 | + |
| 48 | + return plaintext, nil |
| 49 | +} |
| 50 | + |
| 51 | +func (c *EncryptedCache) Put(ctx context.Context, key string, data []byte) error { |
| 52 | + // Select a random nonce, and leave capacity for the ciphertext. |
| 53 | + nonce := make([]byte, c.aead.NonceSize(), c.aead.NonceSize()+len(data)+c.aead.Overhead()) |
| 54 | + if _, err := cryptorand.Read(nonce); err != nil { |
| 55 | + return err |
| 56 | + } |
| 57 | + |
| 58 | + // Encrypt the message and append the ciphertext to the nonce. |
| 59 | + encryptedData := c.aead.Seal(nonce, nonce, data, []byte(key)) |
| 60 | + |
| 61 | + return c.next.Put(ctx, key, encryptedData) |
| 62 | +} |
| 63 | + |
| 64 | +func (c *EncryptedCache) Delete(ctx context.Context, key string) error { |
| 65 | + return c.next.Delete(ctx, key) |
| 66 | +} |
0 commit comments