[go] Go 언어에서의 AES 암호화
AES (Advanced Encryption Standard)는 현대적인 대칭 키 암호화 알고리즘 중 하나입니다. Go 언어에서는 crypto/aes
패키지를 사용하여 AES 암호화를 구현할 수 있습니다.
AES 암호화 키 생성
AES는 128, 192 또는 256비트의 키를 사용합니다. Go 언어에서 AES 암호화 키를 생성하려면 crypto/rand
패키지를 사용하여 랜덤한 키를 생성합니다.
package main
import (
"crypto/aes"
"crypto/cipher"
"crypto/rand"
"fmt"
"io"
)
func main() {
key := make([]byte, 32)
if _, err := rand.Read(key); err != nil {
panic(err)
}
// 생성된 키 출력
fmt.Printf("AES 키: %x\n", key)
}
텍스트 암호화 및 복호화
다음으로, 생성한 키를 사용하여 텍스트를 암호화하고 복호화할 수 있습니다.
package main
import (
"crypto/aes"
"crypto/cipher"
"crypto/rand"
"encoding/hex"
"fmt"
"io"
)
func encrypt(key []byte, text []byte) []byte {
c, err := aes.NewCipher(key)
if err != nil {
panic(err)
}
gcm, err := cipher.NewGCM(c)
if err != nil {
panic(err)
}
nonce := make([]byte, gcm.NonceSize())
if _, err = io.ReadFull(rand.Reader, nonce); err != nil {
panic(err)
}
return gcm.Seal(nonce, nonce, text, nil)
}
func decrypt(key []byte, ciphertext []byte) []byte {
c, err := aes.NewCipher(key)
if err != nil {
panic(err)
}
gcm, err := cipher.NewGCM(c)
if err != nil {
panic(err)
}
nonceSize := gcm.NonceSize()
nonce, ciphertext := ciphertext[:nonceSize], ciphertext[nonceSize:]
decrypted, err := gcm.Open(nil, nonce, ciphertext, nil)
if err != nil {
panic(err)
}
return decrypted
}
func main() {
key := make([]byte, 32)
if _, err := rand.Read(key); err != nil {
panic(err)
}
text := []byte("암호화할 내용")
// 암호화
encrypted := encrypt(key, text)
fmt.Printf("암호화된 데이터: %s\n", hex.EncodeToString(encrypted))
// 복호화
decrypted := decrypt(key, encrypted)
fmt.Printf("복호화된 데이터: %s\n", decrypted)
}
이제 Go 언어를 사용하여 AES 암호화를 구현하는 방법을 알게 되었습니다. AES 암호화에 대해 더 많이 학습하고 싶다면 여기를 참조하세요.