| 1 |
package crypto |
| 2 |
|
| 3 |
import ( |
| 4 |
"bytes" |
| 5 |
"crypto/aes" |
| 6 |
"crypto/cipher" |
| 7 |
"crypto/hkdf" |
| 8 |
"crypto/sha256" |
| 9 |
"encoding/base64" |
| 10 |
"errors" |
| 11 |
"fmt" |
| 12 |
"io" |
| 13 |
"strconv" |
| 14 |
"strings" |
| 15 |
"sync" |
| 16 |
"time" |
| 17 |
) |
| 18 |
|
| 19 |
const ( |
| 20 |
aes256KeySize = 32 |
| 21 |
aesGCMNonceSize = 12 |
| 22 |
aesGCMTagSize = 16 |
| 23 |
keyDerivationInfo = "aes-256-gcm" |
| 24 |
defaultMaxAge = 2 * time.Minute |
| 25 |
|
| 26 |
// timedPlainTextScratchSize covers typical authentication payloads while append retains a heap fallback. |
| 27 |
timedPlainTextScratchSize = 128 |
| 28 |
timedEncryptedScratchSize = timedPlainTextScratchSize + aesGCMNonceSize + aesGCMTagSize |
| 29 |
base64SourceChunkSize = timedEncryptedScratchSize - timedEncryptedScratchSize%3 |
| 30 |
base64EncodedChunkSize = base64SourceChunkSize / 3 * 4 |
| 31 |
) |
| 32 |
|
| 33 |
// ErrCipherTextBlockSize is returned when the ciphertext block size is too short. |
| 34 |
var ErrCipherTextBlockSize = errors.New("ciphertext block size is too short") |
| 35 |
|
| 36 |
// ErrAuthenticationFailed is returned when ciphertext authentication fails. |
| 37 |
var ErrAuthenticationFailed = errors.New("ciphertext authentication failed") |
| 38 |
|
| 39 |
// Cipher provides authenticated encryption using AES-256-GCM. |
| 40 |
type Cipher struct { |
| 41 |
scratchPool sync.Pool |
| 42 |
aead cipher.AEAD |
| 43 |
maxAge time.Duration |
| 44 |
} |
| 45 |
|
| 46 |
// pooledScratch keeps timed-encryption and decryption scratch between calls. |
| 47 |
type pooledScratch struct { |
| 48 |
encrypted [timedEncryptedScratchSize]byte |
| 49 |
} |
| 50 |
|
| 51 |
// New creates a new Cipher instance with the given encryption key. |
| 52 |
// The AEAD key is derived from the input with HKDF-SHA256. The raw key string is |
| 53 |
// not retained in the Cipher after construction. |
| 54 |
func New(encryptionKey string) (*Cipher, error) { |
| 55 |
return NewWithMaxAge(encryptionKey, defaultMaxAge) |
| 56 |
} |
| 57 |
|
| 58 |
// NewWithMaxAge creates a new Cipher instance with the given encryption key and |
| 59 |
// maximum age for timestamped payloads. |
| 60 |
func NewWithMaxAge(encryptionKey string, maxAge time.Duration) (*Cipher, error) { |
| 61 |
key, err := DeriveKey(encryptionKey) |
| 62 |
if err != nil { |
| 63 |
return nil, fmt.Errorf("derive aes-256 key: %w", err) |
| 64 |
} |
| 65 |
defer clear(key[:]) |
| 66 |
|
| 67 |
block, err := aes.NewCipher(key[:]) |
| 68 |
if err != nil { |
| 69 |
return nil, fmt.Errorf("create aes cipher: %w", err) |
| 70 |
} |
| 71 |
|
| 72 |
aead, err := cipher.NewGCMWithRandomNonce(block) |
| 73 |
if err != nil { |
| 74 |
return nil, fmt.Errorf("create aes-gcm: %w", err) |
| 75 |
} |
| 76 |
|
| 77 |
result := &Cipher{ |
| 78 |
aead: aead, |
| 79 |
maxAge: maxAge, |
| 80 |
} |
| 81 |
result.scratchPool.New = func() any { |
| 82 |
return new(pooledScratch) |
| 83 |
} |
| 84 |
|
| 85 |
return result, nil |
| 86 |
} |
| 87 |
|
| 88 |
// DeriveKey derives a 32-byte AES-256 key using HKDF-SHA256. |
| 89 |
func DeriveKey(key string) (*[32]byte, error) { |
| 90 |
derivedKey, err := hkdf.Key(sha256.New, []byte(key), nil, keyDerivationInfo, aes256KeySize) |
| 91 |
if err != nil { |
| 92 |
return nil, fmt.Errorf("hkdf-sha256: %w", err) |
| 93 |
} |
| 94 |
defer clear(derivedKey) |
| 95 |
|
| 96 |
var result [32]byte |
| 97 |
copy(result[:], derivedKey) |
| 98 |
|
| 99 |
return &result, nil |
| 100 |
} |
| 101 |
|
| 102 |
// EncryptBytes encrypts and authenticates data using AES-256-GCM. |
| 103 |
func (c *Cipher) EncryptBytes(plainText []byte) ([]byte, error) { |
| 104 |
return c.encryptBytesInto(nil, plainText) |
| 105 |
} |
| 106 |
|
| 107 |
// DecryptBytes decrypts data encrypted with EncryptBytes. |
| 108 |
func (c *Cipher) DecryptBytes(encryptedData []byte) ([]byte, error) { |
| 109 |
if len(encryptedData) < c.aead.Overhead() { |
| 110 |
return nil, ErrCipherTextBlockSize |
| 111 |
} |
| 112 |
|
| 113 |
return c.decryptBytesInto(nil, encryptedData) |
| 114 |
} |
| 115 |
|
| 116 |
// EncryptBytesWithTime prefixes plaintext with the current Unix timestamp, |
| 117 |
// encrypts it, and returns raw URL-base64 bytes. |
| 118 |
func (c *Cipher) EncryptBytesWithTime(plainText []byte) ([]byte, error) { |
| 119 |
scratch := c.getScratch() |
| 120 |
defer c.putScratch(scratch) |
| 121 |
|
| 122 |
encrypted, err := c.encryptTimedBytes(scratch.encrypted[:0], plainText) |
| 123 |
if err != nil { |
| 124 |
return nil, err |
| 125 |
} |
| 126 |
|
| 127 |
encryptedBase64 := make([]byte, base64.RawURLEncoding.EncodedLen(len(encrypted))) |
| 128 |
|
| 129 |
base64.RawURLEncoding.Encode(encryptedBase64, encrypted) |
| 130 |
|
| 131 |
return encryptedBase64, nil |
| 132 |
} |
| 133 |
|
| 134 |
// EncryptStringWithTime prefixes plaintext with the current Unix timestamp, |
| 135 |
// encrypts it, and returns a raw URL-base64 string. |
| 136 |
func (c *Cipher) EncryptStringWithTime(plainText []byte) (string, error) { |
| 137 |
scratch := c.getScratch() |
| 138 |
defer c.putScratch(scratch) |
| 139 |
|
| 140 |
encrypted, err := c.encryptTimedBytes(scratch.encrypted[:0], plainText) |
| 141 |
if err != nil { |
| 142 |
return "", err |
| 143 |
} |
| 144 |
|
| 145 |
return encodeRawURLBase64String(encrypted), nil |
| 146 |
} |
| 147 |
|
| 148 |
// DecryptBytesWithTime decodes, authenticates, decrypts, and validates the timestamp on raw URL-base64 input. |
| 149 |
func (c *Cipher) DecryptBytesWithTime(encryptedBase64 []byte) ([]byte, error) { |
| 150 |
if err := checkTokenSize(len(encryptedBase64)); err != nil { |
| 151 |
return nil, err |
| 152 |
} |
| 153 |
|
| 154 |
encrypted := make([]byte, base64.RawURLEncoding.DecodedLen(len(encryptedBase64))) |
| 155 |
|
| 156 |
decodedLen, err := base64.RawURLEncoding.Decode(encrypted, encryptedBase64) |
| 157 |
if err != nil { |
| 158 |
return nil, fmt.Errorf("base64 decode %q: %w", encryptedBase64, err) |
| 159 |
} |
| 160 |
|
| 161 |
return c.decryptTimedPayload(encrypted[:decodedLen]) |
| 162 |
} |
| 163 |
|
| 164 |
// DecryptStringWithTime decodes, authenticates, decrypts, and validates |
| 165 |
// the timestamp on raw URL-base64 string input. |
| 166 |
func (c *Cipher) DecryptStringWithTime(encryptedBase64 string) ([]byte, error) { |
| 167 |
if err := checkTokenSize(len(encryptedBase64)); err != nil { |
| 168 |
return nil, err |
| 169 |
} |
| 170 |
|
| 171 |
encrypted, err := base64.RawURLEncoding.DecodeString(encryptedBase64) |
| 172 |
if err != nil { |
| 173 |
return nil, fmt.Errorf("base64 decode %q: %w", encryptedBase64, err) |
| 174 |
} |
| 175 |
|
| 176 |
return c.decryptTimedPayload(encrypted) |
| 177 |
} |
| 178 |
|
| 179 |
// DecryptStringWithTimeInto decodes, authenticates, decrypts, and validates |
| 180 |
// raw URL-base64 input into dst. On success, it returns the plaintext length. |
| 181 |
// If dst is too short, it returns the required decoded capacity with io.ErrShortBuffer. |
| 182 |
func (c *Cipher) DecryptStringWithTimeInto(dst []byte, encryptedBase64 string) (int, error) { |
| 183 |
if err := checkTokenSize(len(encryptedBase64)); err != nil { |
| 184 |
return 0, err |
| 185 |
} |
| 186 |
|
| 187 |
decodedLen := base64.RawURLEncoding.DecodedLen(len(encryptedBase64)) |
| 188 |
if len(dst) < decodedLen { |
| 189 |
return decodedLen, io.ErrShortBuffer |
| 190 |
} |
| 191 |
|
| 192 |
scratch := c.getScratch() |
| 193 |
defer c.putScratch(scratch) |
| 194 |
|
| 195 |
var encrypted []byte |
| 196 |
if decodedLen > cap(scratch.encrypted) { |
| 197 |
encrypted = make([]byte, decodedLen) |
| 198 |
} else { |
| 199 |
encrypted = scratch.encrypted[:decodedLen] |
| 200 |
} |
| 201 |
|
| 202 |
decodedLen, err := base64.RawURLEncoding.Decode(encrypted, []byte(encryptedBase64)) |
| 203 |
if err != nil { |
| 204 |
return 0, fmt.Errorf("base64 decode %q: %w", encryptedBase64, err) |
| 205 |
} |
| 206 |
|
| 207 |
plainText, err := c.decryptTimedPayload(encrypted[:decodedLen]) |
| 208 |
if err != nil { |
| 209 |
return 0, err |
| 210 |
} |
| 211 |
|
| 212 |
return copy(dst, plainText), nil |
| 213 |
} |
| 214 |
|
| 215 |
// encryptTimedBytes prefixes plaintext with a timestamp and encrypts it into dst. |
| 216 |
func (c *Cipher) encryptTimedBytes(dst, plainText []byte) ([]byte, error) { |
| 217 |
issued := time.Now().Round(time.Second).Unix() |
| 218 |
|
| 219 |
var scratch [timedPlainTextScratchSize]byte |
| 220 |
|
| 221 |
timedPlainText := strconv.AppendInt(scratch[:0], issued, 10) |
| 222 |
timedPlainText = append(timedPlainText, ' ') |
| 223 |
timedPlainText = append(timedPlainText, plainText...) |
| 224 |
|
| 225 |
return c.encryptBytesInto(dst, timedPlainText) |
| 226 |
} |
| 227 |
|
| 228 |
func encodeRawURLBase64String(src []byte) string { |
| 229 |
var encoded strings.Builder |
| 230 |
encoded.Grow(base64.RawURLEncoding.EncodedLen(len(src))) |
| 231 |
|
| 232 |
var scratch [base64EncodedChunkSize]byte |
| 233 |
|
| 234 |
for len(src) > base64SourceChunkSize { |
| 235 |
base64.RawURLEncoding.Encode(scratch[:], src[:base64SourceChunkSize]) |
| 236 |
_, _ = encoded.Write(scratch[:]) |
| 237 |
|
| 238 |
src = src[base64SourceChunkSize:] |
| 239 |
} |
| 240 |
|
| 241 |
encodedLen := base64.RawURLEncoding.EncodedLen(len(src)) |
| 242 |
base64.RawURLEncoding.Encode(scratch[:encodedLen], src) |
| 243 |
_, _ = encoded.Write(scratch[:encodedLen]) |
| 244 |
|
| 245 |
return encoded.String() |
| 246 |
} |
| 247 |
|
| 248 |
// encryptBytesInto encrypts plainText into dst, allocating only when its capacity is insufficient. |
| 249 |
func (c *Cipher) encryptBytesInto(dst, plainText []byte) ([]byte, error) { |
| 250 |
resultSize := len(plainText) + c.aead.Overhead() |
| 251 |
|
| 252 |
if cap(dst) < resultSize { |
| 253 |
dst = make([]byte, 0, resultSize) |
| 254 |
} else { |
| 255 |
dst = dst[:0] |
| 256 |
} |
| 257 |
|
| 258 |
return c.aead.Seal(dst, nil, plainText, nil), nil |
| 259 |
} |
| 260 |
|
| 261 |
// decryptBytesInto authenticates encryptedData and decrypts it into dst. |
| 262 |
// Callers must reject ciphertext shorter than the nonce and authentication tag. |
| 263 |
func (c *Cipher) decryptBytesInto(dst, encryptedData []byte) ([]byte, error) { |
| 264 |
plainText, err := c.aead.Open(dst, nil, encryptedData, nil) |
| 265 |
if err != nil { |
| 266 |
return nil, ErrAuthenticationFailed |
| 267 |
} |
| 268 |
|
| 269 |
return plainText, nil |
| 270 |
} |
| 271 |
|
| 272 |
// decryptTimedPayload authenticates, decrypts, and validates |
| 273 |
// an already base64-decoded timestamped payload. |
| 274 |
func (c *Cipher) decryptTimedPayload(encrypted []byte) ([]byte, error) { |
| 275 |
if len(encrypted) < c.aead.Overhead() { |
| 276 |
return nil, ErrCipherTextBlockSize |
| 277 |
} |
| 278 |
|
| 279 |
data, err := c.decryptBytesInto( |
| 280 |
encrypted[:0], |
| 281 |
encrypted, |
| 282 |
) |
| 283 |
if err != nil { |
| 284 |
return nil, err |
| 285 |
} |
| 286 |
|
| 287 |
issued, data, err := extractIssued(data) |
| 288 |
if err != nil { |
| 289 |
return nil, err |
| 290 |
} |
| 291 |
|
| 292 |
if err := c.validateIssued(issued); err != nil { |
| 293 |
return nil, err |
| 294 |
} |
| 295 |
|
| 296 |
return data, nil |
| 297 |
} |
| 298 |
|
| 299 |
// getScratch returns reusable scratch for timed encryption and decryption. |
| 300 |
func (c *Cipher) getScratch() *pooledScratch { |
| 301 |
scratch, ok := c.scratchPool.Get().(*pooledScratch) |
| 302 |
if !ok { |
| 303 |
return new(pooledScratch) |
| 304 |
} |
| 305 |
|
| 306 |
return scratch |
| 307 |
} |
| 308 |
|
| 309 |
// putScratch clears plaintext before returning scratch to the pool. |
| 310 |
func (c *Cipher) putScratch(scratch *pooledScratch) { |
| 311 |
clear(scratch.encrypted[:]) |
| 312 |
c.scratchPool.Put(scratch) |
| 313 |
} |
| 314 |
|
| 315 |
// checkTokenSize rejects unreasonably large encoded payloads before allocating decode buffers. |
| 316 |
func checkTokenSize(encodedLength int) error { |
| 317 |
if encodedLength > 4096 { |
| 318 |
return fmt.Errorf("%w: token too large", ErrInvalid) |
| 319 |
} |
| 320 |
|
| 321 |
return nil |
| 322 |
} |
| 323 |
|
| 324 |
// extractIssued extracts the issued timestamp from the decrypted data. |
| 325 |
// The timestamp is stored as a string followed by a space at the beginning of the data. |
| 326 |
func extractIssued(data []byte) (int64, []byte, error) { |
| 327 |
// Find the space separator |
| 328 |
before, after, ok := bytes.Cut(data, []byte{' '}) |
| 329 |
|
| 330 |
if !ok { |
| 331 |
return 0, nil, errors.New("invalid data format: no timestamp found") |
| 332 |
} |
| 333 |
|
| 334 |
// Parse the timestamp |
| 335 |
issued, err := strconv.ParseInt(string(before), 10, 64) |
| 336 |
if err != nil { |
| 337 |
return 0, nil, fmt.Errorf("parse issued timestamp: %w", err) |
| 338 |
} |
| 339 |
|
| 340 |
// Return the timestamp and the remaining data (after the space) |
| 341 |
return issued, after, nil |
| 342 |
} |
| 343 |
|
| 344 |
// validateIssued checks that the issued timestamp is within the accepted clock window. |
| 345 |
func (c *Cipher) validateIssued(issued int64) error { |
| 346 |
issuedSince := time.Since(time.Unix(issued, 0)) |
| 347 |
|
| 348 |
if issuedSince >= c.maxAge { |
| 349 |
return fmt.Errorf("%w: expired after %s, issued at: %s", ErrInvalid, c.maxAge, issuedSince.String()) |
| 350 |
} |
| 351 |
|
| 352 |
if issuedSince <= time.Second*-5 { |
| 353 |
return fmt.Errorf("%w: issued in future, issued at: %s", ErrInvalid, issuedSince.String()) |
| 354 |
} |
| 355 |
|
| 356 |
return nil |
| 357 |
} |