Enkripsi & Dekripsi Data di Go Pakai AES (Contoh Praktis)
Kalau kamu bikin aplikasi yang butuh ngamanin data (misalnya password, token, atau informasi sensitif), kamu pasti perlu enkripsi. Salah satu algoritma paling populer dan kuat adalah AES (Advanced Encryption Standard).
Di Go, saya bisa pakai AES dengan cukup mudah lewat paket bawaan crypto/aes dan crypto/cipher. Dalam contoh ini, saya bakal pakai mode CFB (Cipher Feedback) karena fleksibel dan bisa langsung dipakai buat data dengan panjang sembarang.
Konsep Singkat AES Simetris: kunci yang dipakai buat enkripsi dan dekripsi sama. IV (Initialization Vector): angka acak yang bikin hasil enkripsi beda-beda walaupun plaintext-nya sama. CFB mode: mode enkripsi yang cocok buat data bergaya stream, jadi nggak perlu padding ribet. Contoh Program Go Copy package main import ( "crypto/aes" "crypto/cipher" "crypto/rand" "encoding/base64" "fmt" "io" ) func generateRandomKey() ([]byte, error) { key := make([]byte, 32) // AES-256 _, err := rand.Read(key) if err != nil { return nil, err } return key, nil } func encrypt(plaintext []byte, key []byte) ([]byte, error) { block, err := aes.NewCipher(key) if err != nil { return nil, err } ciphertext := make([]byte, aes.BlockSize+len(plaintext)) iv := ciphertext[:aes.BlockSize] if _, err := io.ReadFull(rand.Reader, iv); err != nil { return nil, err } stream := cipher.NewCFBEncrypter(block, iv) stream.XORKeyStream(ciphertext[aes.BlockSize:], plaintext) return ciphertext, nil } func decrypt(ciphertext []byte, key []byte) ([]byte, error) { block, err := aes.NewCipher(key) if err != nil { return nil, err } if len(ciphertext) < aes.BlockSize { return nil, fmt.Errorf("ciphertext too short") } iv := ciphertext[:aes.BlockSize] ciphertext = ciphertext[aes.BlockSize:] stream := cipher.NewCFBDecrypter(block, iv) stream.XORKeyStream(ciphertext, ciphertext) return ciphertext, nil } func main() { plaintext := []byte("Ini data rahasia yang harus diamankan 🔒") key, _ := generateRandomKey() ciphertext, _ := encrypt(plaintext, key) fmt.Println("Ciphertext (base64):", base64.StdEncoding.EncodeToString(ciphertext)) decrypted, _ := decrypt(ciphertext, key) fmt.Println("Decrypted text:", string(decrypted)) } Cara Kerjanya Bikin kunci acak (generateRandomKey) → panjang 32 byte (AES-256). Enkripsi (encrypt) → bikin IV acak, lalu enkripsi plaintext pakai AES-CFB. Dekripsi (decrypt) → ambil IV dari awal ciphertext, lalu kembalikan data ke bentuk asli. Main → demonya: enkripsi string, print hasil base64, lalu dekripsi lagi buat bukti bahwa datanya aman bolak-balik. Output Contoh Copy Ciphertext (base64): QZrR9m0dpN9Yk3cGYn1xY1Hu0+8EJz6fC4oYc5V1qDqPV6Y= Decrypted text: Ini data rahasia yang harus diamankan Kesimpulan Dengan AES + CFB mode di Go: