因為專案的關係需要用到 aes-gcm 就把它封裝成 function 來方便平常使用
AES-GCM
package main import ( "crypto/aes" "crypto/cipher" "fmt" ) func encrypt(plaintext, key, nonce []byte) []byte { block, err := aes.NewCipher(key) if err != nil { panic(err.Error()) } aesgcm, err := cipher.NewGCM(block) if err != nil { panic(err.Error()) } ciphertext := aesgcm.Seal(nil, nonce, plaintext, nil) return ciphertext } func decrypt(ciphertext, key, nonce []byte) []byte { block, err := aes.NewCipher(key) if err != nil { panic(err.Error()) } aesgcm, err := cipher.NewGCM(block) if err != nil { panic(err.Error()) } plaintext, err := aesgcm.Open(nil, nonce, ciphertext, nil) if err != nil { panic(err.Error()) } return plaintext } func main() { fmt.Println("AES encryption with GCM") plaintext := []byte("Some plain text") key := []byte("secretkey32bytessecretkey32bytes") nonce := make([]byte, 12) ciphertext := encrypt(plaintext, key, nonce) fmt.Printf("Ciphertext: %x\n", ciphertext) recoveredPt := decrypt(ciphertext, key, nonce) fmt.Printf("Recovered plaintext: %s\n", recoveredPt) }
完成後需要使用到 AES-GCM 只需要用到兩個 function 分別是 encrypt 與 decrypt,也就是加密與解密,放入的參數有:原始資料、密碼與 nonce,這邊要注意密碼的部分只能是 16 bytes 或是 32 bytes,分別對應到 AES–128–GCM 與 AES-256-GCM。
《AWS CDK 完全學習手冊:打造雲端基礎架構程式碼 IaC》
第 12 屆 iT 邦幫忙鐵人賽 DevOps 組冠的《用 CDK 定 義 AWS 架構》
第 11 屆 iT 邦幫忙鐵人賽《LINE bot 好好玩 30 天玩轉 LINE API》
一個熱愛分享的雲端工程師!