[go] go 언어의 암호화 통신 레이어 구현
암호화된 통신은 데이터의 안전한 전송을 보장하기 위해 매우 중요합니다. Go 언어로 간단하게 SSL/TLS 및 암호화된 통신을 구현하는 방법을 알아보겠습니다.
1. SSL/TLS를 이용한 안전한 통신 설정
package main
import (
"crypto/tls"
"net/http"
)
func main() {
tr := &http.Transport{
TLSClientConfig: &tls.Config{InsecureSkipVerify: true}, // 인증서 유효성 검사 비활성화(테스트용)
}
client := &http.Client{Transport: tr}
resp, err := client.Get("https://example.com")
if err != nil {
// 에러 처리
}
defer resp.Body.Close()
// 응답 처리
}
위 예제에서는 https://example.com
으로 GET 요청을 보내고 있습니다. crypto/tls
패키지를 사용하여 TLS 설정을 생성하고, http.Transport
를 통해 클라이언트에 설정합니다.
2. 데이터 암호화 및 복호화
package main
import (
"crypto/aes"
"crypto/cipher"
"crypto/rand"
"fmt"
"io"
)
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() {
key := []byte("very-secret-key")
plaintext := []byte("안녕, Go 언어!")
fmt.Printf("평문: %s\n", plaintext)
ciphertext, err := encrypt(plaintext, key)
if err != nil {
// 에러 처리
}
decrypted, err := decrypt(ciphertext, key)
if err != nil {
// 에러 처리
}
fmt.Printf("복호화된 결과: %s\n", decrypted)
}
위 코드에서는 crypto/aes
및 crypto/cipher
패키지를 사용하여 데이터를 AES 알고리즘을 이용해 암호화하고 복호화하는 예제를 보여주고 있습니다.
이제 Go 언어를 사용하여 안전한 통신 및 데이터 암호화를 간단하게 구현하는 방법에 대해 알아보았습니다. 이러한 기술들을 적절히 활용하여 안전한 통신 및 데이터 보안을 강화할 수 있습니다.
참고 문헌:
- https://golang.org/pkg/crypto/tls/
- https://pkg.go.dev/crypto/aes