Lab 11: Security Architecture

Time: 60 minutes | Level: Architect | Docker: golang:1.22-alpine

Overview

Go security architecture: golang.org/x/crypto (chacha20poly1305/argon2/ed25519/x25519), secure random, PASETO-style tokens (HMAC-SHA512), mTLS, security headers middleware, and token bucket rate limiting.


Step 1: Symmetric Encryption — XChaCha20-Poly1305

package crypto

import (
	"crypto/rand"
	"errors"
	"golang.org/x/crypto/chacha20poly1305"
)

// XChaCha20-Poly1305: authenticated encryption (AEAD)
// 256-bit key, 192-bit nonce (XChaCha = extended nonce, safe for random generation)
// Authenticates both ciphertext + associated data (prevents tampering)

func Encrypt(key []byte, plaintext []byte) ([]byte, error) {
	if len(key) != chacha20poly1305.KeySize { // 32 bytes
		return nil, errors.New("key must be 32 bytes")
	}

	aead, err := chacha20poly1305.NewX(key)
	if err != nil {
		return nil, err
	}

	// Random 192-bit nonce — XChaCha extended nonce is safe to generate randomly
	nonce := make([]byte, aead.NonceSize()) // 24 bytes
	if _, err = rand.Read(nonce); err != nil {
		return nil, err
	}

	// Seal: encrypt + authenticate
	// Output: nonce || ciphertext+tag
	ciphertext := aead.Seal(nonce, nonce, plaintext, nil)
	return ciphertext, nil
}

func Decrypt(key []byte, ciphertext []byte) ([]byte, error) {
	aead, err := chacha20poly1305.NewX(key)
	if err != nil {
		return nil, err
	}

	nonceSize := aead.NonceSize()
	if len(ciphertext) < nonceSize+aead.Overhead() {
		return nil, errors.New("ciphertext too short")
	}

	nonce, ciphertext := ciphertext[:nonceSize], ciphertext[nonceSize:]
	return aead.Open(nil, nonce, ciphertext, nil)
}

Step 2: Password Hashing — Argon2id


Step 3: Asymmetric Keys — Ed25519 + X25519


Step 4: PASETO-Style Tokens (HMAC-SHA512)


Step 5: Security Headers Middleware


Step 6: Token Bucket Rate Limiting


Step 7: Secrets Management Pattern


Step 8: Capstone — Encryption + Ed25519

📸 Verified Output:


Summary

Algorithm
Use Case
Security Level

XChaCha20-Poly1305

Symmetric AEAD encryption

256-bit

Argon2id

Password hashing

OWASP recommended

Ed25519

Digital signatures

128-bit equivalent

X25519

Key exchange (ECDH)

128-bit equivalent

HMAC-SHA512

Token authentication

256-bit effective

Token bucket

Rate limiting

DoS protection

Security headers

HTTP hardening

OWASP Top 10

Secret[T]

Prevent accidental leaks

Type-safe redaction

Last updated