Lab 13: TLS & Crypto

Time: 45 minutes | Level: Advanced | Docker: docker run -it --rm golang:1.22-alpine sh

Overview

Master Go's cryptography stack: self-signed certificates with x509, mTLS server/client, AES-256-GCM encryption, SHA-256 hashing, bcrypt password hashing, and ECDSA key generation.


Step 1: ECDSA Key Generation

package main

import (
	"crypto/ecdsa"
	"crypto/elliptic"
	"crypto/rand"
	"crypto/x509"
	"encoding/pem"
	"fmt"
	"os"
)

func generateECDSAKey() (*ecdsa.PrivateKey, error) {
	// P-256 (secp256r1) — NIST curve, widely supported
	return ecdsa.GenerateKey(elliptic.P256(), rand.Reader)
}

func savePrivateKey(key *ecdsa.PrivateKey, path string) error {
	keyDER, err := x509.MarshalECPrivateKey(key)
	if err != nil {
		return err
	}
	f, err := os.Create(path)
	if err != nil {
		return err
	}
	defer f.Close()
	return pem.Encode(f, &pem.Block{Type: "EC PRIVATE KEY", Bytes: keyDER})
}

func main() {
	key, err := generateECDSAKey()
	if err != nil {
		panic(err)
	}
	fmt.Printf("ECDSA key: curve=%s\n", key.Curve.Params().Name)
	fmt.Printf("Public key X: %x\n", key.X.Bytes()[:8]) // first 8 bytes
}

Step 2: Self-Signed Certificate


Step 3: mTLS Server and Client


Step 4: AES-256-GCM Encryption


Step 5: SHA-256 and HMAC


Step 6: bcrypt Password Hashing


Step 7: Complete Crypto Demo

📸 Verified Output:


Step 8: Capstone — mTLS Demo (In-Process)


Summary

Algorithm
Package
Use Case

ECDSA P-256

crypto/ecdsa

Key generation, signing

Self-signed cert

crypto/x509

Development TLS

mTLS

crypto/tls

Service-to-service auth

AES-256-GCM

crypto/aes + crypto/cipher

Symmetric encryption

SHA-256

crypto/sha256

Integrity hashing

HMAC-SHA256

crypto/hmac

Authenticated hashing

bcrypt

golang.org/x/crypto/bcrypt

Password storage

Key Takeaways:

  • AES-GCM provides both encryption AND authentication (AEAD)

  • Never reuse a nonce with the same key — generate fresh random nonce each time

  • hmac.Equal uses constant-time comparison to prevent timing attacks

  • mTLS authenticates both server AND client with certificates

  • bcrypt cost 12 is a good default — increase over time as hardware gets faster

  • Never store plaintext passwords — always use bcrypt/argon2/scrypt

Last updated