Security. Dili ni optional — kung seryoso ka sa imong app, dapat kabalo ka ani. Anhi nga chapter: common vulnerabilities (SQL injection, XSS, command injection) ug Go crypto libraries para hashing, encryption, TLS, ug password management. Ayawg sige rag send ug password sa plain text, tawn.
Ang Go design nag-reduce ug daghang security risks — memory safety, walay buffer overflows, ug strong type system. Pero ang application-level vulnerabilities (injection, XSS, broken auth) pwedeng mahitabo. Magsulat ug defensive code: i-validate input, i-sanitize output, gamit ug parameterized queries, ug i-update ang dependencies. Ayaw sige ug copy-paste sa Stack Overflow nga walay sabot.
Ang SQL injection mahitabo kung ang user input gi-concatenate diretso sa SQL queries. Ayaw jud himoa ni — mas bati pa ni kaysa mangutang ka sa 5-6:
// Vulnerable — ayaw jud ni!
username := r.FormValue("username")
query := "SELECT * FROM users WHERE name = '" + username + "'"
rows, _ := db.Query(query)
// Always use parameterized queries:
rows, _ := db.Query("SELECT * FROM users WHERE name = ?", username)
Ang command injection mahitabo kung ang user input gi-pass sa shell commands. Likayan ang pag-run ug shell commands na may user input. Gamit ug Go os/exec na separate arguments, dili shell strings — ayawg sige ug sh -c kung wa ka kabalo:
// Vulnerable:
userInput := "file.txt; rm -rf /"
cmd := exec.Command("sh", "-c", "cat "+userInput)
// Safe:
cmd := exec.Command("cat", "file.txt") // walay shell involved
Goal: Ipakita ang difference between vulnerable query building ug safe parameterized queries. Ayawg maging tanga — mao ni difference sa husto ug sayop:
package main
import (
"database/sql"
"fmt"
_ "github.com/mattn/go-sqlite3"
)
func main() {
db, _ := sql.Open("sqlite3", ":memory:")
db.Exec("CREATE TABLE users (id INTEGER, name TEXT)")
db.Exec("INSERT INTO users VALUES (1, 'alice'), (2, 'bob')")
// Safe — parameterized query
input := "alice"
row := db.QueryRow("SELECT id FROM users WHERE name = ?", input)
var id int
row.Scan(&id)
fmt.Println("Safe query found ID:", id)
// input with SQL injection attempt
input = "alice' OR '1'='1"
// Never concatenate: "SELECT id FROM users WHERE name = '" + input + "'"
row = db.QueryRow("SELECT id FROM users WHERE name = ?", input)
err := row.Scan(&id)
fmt.Println("Injection attempt:", err) // no rows — safe
}
Ang XSS mahitabo kung ang user input gi-render sa HTML na walay escaping. Ang Go html/template package awtomatikong nag-escape ug output. Always gamit ug html/template (dili text/template) para HTML contexts — ang text/template wa ray labot sa imong HTML, di ka tabangan:
tmpl := template.Must(template.New("page").Parse(
"Hello, {{.Name}}!
",
))
// Kung ang .Name kay "",
// ma-render as text, dili i-execute nga JavaScript.
tmpl.Execute(w, struct{ Name string }{""})
Goal: Ipakita kung pano ang html/template nag-prevent ug XSS pinaagi sa pag-escape ug malicious input. I-escape jud niya — wa ray labot kung unsa ka creative imong hacker:
package main
import (
"html/template"
"os"
)
func main() {
tmpl := template.Must(template.New("page").Parse(
"User comment: {{.Comment}}",
))
// Malicious input — template escapes it
tmpl.Execute(os.Stdout, struct{ Comment string }{
Comment: "",
})
// Output: User comment: <script>alert('hacked')</script>
}
Ang Go crypto package nagprovide ug modern, secure cryptographic primitives. Gamit ug high-level packages kung possible — likayan ang pag-implementar ug crypto primitives sa imo kaugalingon. Dili ka si Galileo, ayawg re-invent sa crypto.
Gamit ug crypto/sha256 or crypto/sha512 para hashing. Para passwords, gamit ug golang.org/x/crypto/bcrypt — ayawg sha256 sa password ha, lahi nang conversation:
import (
"crypto/sha256"
"fmt"
)
hash := sha256.Sum256([]byte("password123"))
fmt.Printf("%x\n", hash)
Goal: I-hash ang string gamit SHA-256 ug SHA-512, dayon i-print ang hex output. Tan-awa ang kalainan — mas taas ang SHA-512, mas safe pero mas hinay gamay:
package main
import (
"crypto/sha256"
"crypto/sha512"
"fmt"
)
func main() {
data := []byte("Hello, Go!")
sha256sum := sha256.Sum256(data)
sha512sum := sha512.Sum512(data)
fmt.Printf("SHA-256: %x\n", sha256sum)
fmt.Printf("SHA-512: %x\n", sha512sum)
fmt.Println("SHA-256 length:", len(sha256sum), "bytes")
fmt.Println("SHA-512 length:", len(sha512sum), "bytes")
}
Ang Go supports both symmetric (same key para encrypt/decrypt) ug asymmetric (public/private key) encryption through crypto package. Depende sa imong need, pili lang — pero ayawg gamit ug ROT13, di na tayo bata.
Ang AES encryption na may GCM mode nagprovide ug authenticated encryption. Parehas na key ang mag-encrypt ug decrypt. Gamita ni kung ikaw ra isa ang nag-process sa data. Kung daghan tao, usag-saag:
import (
"crypto/aes"
"crypto/cipher"
"crypto/rand"
)
key := []byte("examplekey1234567") // 16 bytes for AES-128
plaintext := []byte("secret message")
block, _ := aes.NewCipher(key)
aesGCM, _ := cipher.NewGCM(block)
nonce := make([]byte, aesGCM.NonceSize())
rand.Read(nonce)
ciphertext := aesGCM.Seal(nil, nonce, plaintext, nil)
// ciphertext = nonce + encrypted data + auth tag
Goal: I-encrypt ang message gamit AES-GCM ug i-decrypt balik sa original. Encrypt -> decrypt -> original. Kung mag-encrypt ka pero di ka ka-decrypt, naa kay sayup.
package main
import (
"crypto/aes"
"crypto/cipher"
"crypto/rand"
"fmt"
)
func main() {
key := []byte("AESKey1234567890") // 16 bytes
plaintext := []byte("Sensitive data")
block, _ := aes.NewCipher(key)
aesGCM, _ := cipher.NewGCM(block)
nonce := make([]byte, aesGCM.NonceSize())
rand.Read(nonce)
ciphertext := aesGCM.Seal(nil, nonce, plaintext, nil)
fmt.Printf("Encrypted: %x\n", ciphertext)
decrypted, _ := aesGCM.Open(nil, nonce, ciphertext, nil)
fmt.Printf("Decrypted: %s\n", decrypted)
}
Ang RSA nagamit ug public key para i-encrypt ug private key para i-decrypt. Generate keys gamit crypto/rsa. I-share imong public key sa kalibutan, i-private ang imong private key — common sense ni, ayawg ingna wa ka kabalo:
privateKey, _ := rsa.GenerateKey(rand.Reader, 2048)
publicKey := &privateKey.PublicKey
// Encrypt with public key
ciphertext, _ := rsa.EncryptOAEP(sha256.New(), rand.Reader, publicKey, []byte("secret"), nil)
// Decrypt with private key
plaintext, _ := rsa.DecryptOAEP(sha256.New(), rand.Reader, privateKey, ciphertext, nil)
Goal: Generate ug RSA key pair, i-encrypt ang message gamit public key, i-decrypt gamit private key. Public key para mang-lock, private key para ma-unlock. Siyaro maglibog ka:
package main
import (
"crypto/rand"
"crypto/rsa"
"crypto/sha256"
"fmt"
)
func main() {
privateKey, _ := rsa.GenerateKey(rand.Reader, 2048)
publicKey := &privateKey.PublicKey
message := []byte("Secret message")
ciphertext, _ := rsa.EncryptOAEP(sha256.New(), rand.Reader, publicKey, message, nil)
fmt.Printf("Encrypted: %x\n", ciphertext)
plaintext, _ := rsa.DecryptOAEP(sha256.New(), rand.Reader, privateKey, ciphertext, nil)
fmt.Printf("Decrypted: %s\n", plaintext)
}
Gamit ug crypto/rand para cryptographic-quality random numbers — dili math/rand na predictable. Kung security-related imong gamit, math/rand raba kay ma-predict ra. Ayawg gamit ug math/rand para sa imong token — patay ka ana:
import "crypto/rand"
// Generate random bytes
token := make([]byte, 32)
rand.Read(token)
// Generate random integer
n, _ := rand.Int(rand.Reader, big.NewInt(100)) // 0-99
// Generate a hex token
fmt.Printf("%x\n", token)
Goal: Generate ug cryptographically secure random token (32 bytes) ug i-print as hex. Para sa imong API keys, session tokens, o unsa pa na:
package main
import (
"crypto/rand"
"fmt"
)
func main() {
token := make([]byte, 32)
_, err := rand.Read(token)
if err != nil {
fmt.Println("error:", err)
return
}
fmt.Printf("Token: %x\n", token)
fmt.Printf("Length: %d bytes\n", len(token))
}
I-serve ang HTTPS na may certificates gamit http.ListenAndServeTLS or configure ug TLS server manually. Generate self-signed certs para development. Kung production na, ayawg self-signed — palit ug tinuod na cert or gamit ug Let's Encrypt:
go run /usr/local/go/src/crypto/tls/generate_cert.go \
--host localhost
// Then serve:
http.ListenAndServeTLS(":443", "cert.pem", "key.pem", nil)
Goal: Generate ug self-signed TLS certificate programmatically gamit Go crypto library. Kani ang certificate nga murag "I declare this server safe" pero wa ray nag-back:
package main
import (
"crypto/rand"
"crypto/rsa"
"crypto/x509"
"crypto/x509/pkix"
"encoding/pem"
"math/big"
"os"
"time"
)
func main() {
privateKey, _ := rsa.GenerateKey(rand.Reader, 2048)
template := x509.Certificate{
SerialNumber: big.NewInt(1),
Subject: pkix.Name{CommonName: "localhost"},
NotBefore: time.Now(),
NotAfter: time.Now().Add(365 * 24 * time.Hour),
KeyUsage: x509.KeyUsageKeyEncipherment | x509.KeyUsageDigitalSignature,
ExtKeyUsage: []x509.ExtKeyUsage{x509.ExtKeyUsageServerAuth},
}
certDER, _ := x509.CreateCertificate(rand.Reader, &template, &template, &privateKey.PublicKey, privateKey)
certFile, _ := os.Create("cert.pem")
pem.Encode(certFile, &pem.Block{Type: "CERTIFICATE", Bytes: certDER})
certFile.Close()
keyFile, _ := os.Create("key.pem")
pem.Encode(keyFile, &pem.Block{Type: "RSA PRIVATE KEY", Bytes: x509.MarshalPKCS1PrivateKey(privateKey)})
keyFile.Close()
fmt.Println("Generated cert.pem and key.pem")
}
Goal: I-serve ug simple HTTPS server gamit ang generated certificate. Secure na imong connection — dili na magreklamo ang browser (okay, magreklamo japon kung self-signed, pero at least HTTPS na):
package main
import (
"fmt"
"net/http"
)
func main() {
http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
fmt.Fprintf(w, "Secure connection!")
})
fmt.Println("Server running at https://localhost:443")
http.ListenAndServeTLS(":443", "cert.pem", "key.pem", nil)
}
Ayaw jud i-store ang passwords in plain text — 2026 na, tawn. Gamit ug bcrypt para password hashing. May salt ug deliberately slow para resist sa brute force. Kung ganahan kag dugang delay, i-adjust ang cost factor:
import "golang.org/x/crypto/bcrypt"
// Hash a password
hash, _ := bcrypt.GenerateFromPassword([]byte("user-password"), bcrypt.DefaultCost)
// Verify a password
err := bcrypt.CompareHashAndPassword(hash, []byte("user-password"))
if err == nil {
fmt.Println("password correct")
}
Goal: I-simulate ang user registration ug login with bcrypt hashed passwords. Ayawg sige ug fmt.Println sa password ha:
package main
import (
"fmt"
"golang.org/x/crypto/bcrypt"
)
type User struct {
Username string
Password []byte
}
func register(username, password string) User {
hash, _ := bcrypt.GenerateFromPassword([]byte(password), bcrypt.DefaultCost)
return User{Username: username, Password: hash}
}
func login(user User, password string) bool {
err := bcrypt.CompareHashAndPassword(user.Password, []byte(password))
return err == nil
}
func main() {
user := register("alice", "securePass123!")
fmt.Println("User registered:", user.Username)
fmt.Println("Login correct:", login(user, "securePass123!")) // true
fmt.Println("Login wrong:", login(user, "wrongpassword")) // false
}
Goal: Paghimo ug simple CA certificate ug i-sign ang server certificate. Murag imong sariling certification authority — ikaw ang boss, ikaw ang nag-validate:
package main
import (
"crypto/rand"
"crypto/rsa"
"crypto/x509"
"crypto/x509/pkix"
"encoding/pem"
"math/big"
"os"
"time"
)
func createCert(template, parent *x509.Certificate, pub, priv interface{}) {
certDER, _ := x509.CreateCertificate(rand.Reader, template, parent, pub, priv)
pem.Encode(os.Stdout, &pem.Block{Type: "CERTIFICATE", Bytes: certDER})
}
func main() {
caKey, _ := rsa.GenerateKey(rand.Reader, 2048)
caTemplate := x509.Certificate{
SerialNumber: big.NewInt(1),
Subject: pkix.Name{CommonName: "My Root CA"},
NotBefore: time.Now(),
NotAfter: time.Now().Add(10 * 365 * 24 * time.Hour),
IsCA: true,
KeyUsage: x509.KeyUsageCertSign | x509.KeyUsageDigitalSignature,
}
caCertDER, _ := x509.CreateCertificate(rand.Reader, &caTemplate, &caTemplate, &caKey.PublicKey, caKey)
caCert, _ := x509.ParseCertificate(caCertDER)
serverKey, _ := rsa.GenerateKey(rand.Reader, 2048)
serverTemplate := x509.Certificate{
SerialNumber: big.NewInt(2),
Subject: pkix.Name{CommonName: "server.local"},
NotBefore: time.Now(),
NotAfter: time.Now().Add(1 * 365 * 24 * time.Hour),
KeyUsage: x509.KeyUsageKeyEncipherment | x509.KeyUsageDigitalSignature,
ExtKeyUsage: []x509.ExtKeyUsage{x509.ExtKeyUsageServerAuth},
}
fmt.Println("CA Certificate:")
createCert(&caTemplate, caCert, &caKey.PublicKey, caKey)
fmt.Println("\nServer Certificate (signed by CA):")
createCert(&serverTemplate, caCert, &serverKey.PublicKey, caKey)
}
html/template para automatic XSS escapingcrypto/rand para secure random numbers, dili math/randhttp.ListenAndServeTLS