[go] Go 언어에서의 암호화 기능

Go 언어에는 다양한 암호화 기능을 제공하여 데이터를 안전하게 보호하고 통신을 암호화할 수 있습니다. 이 기능들은 암호화된 데이터를 생성하고 처리하는 데 사용될 수 있습니다.

목차

해시 함수

해시 함수는 임의 크기의 데이터를 고정된 크기의 해시 값으로 매핑하는 함수입니다. Go 언어에서는 crypto 패키지를 사용하여 해시 함수를 구현할 수 있습니다.

import (
	"crypto/sha256"
	"fmt"
)

func main() {
	data := []byte("Hello, world!")
	hash := sha256.Sum256(data)
	fmt.Printf("%x", hash)
}

해시 함수를 사용하면 데이터의 무결성을 보장하고, 비밀번호 저장, 메시지 무결성 검사 및 데이터 무결성 확인에 사용할 수 있습니다.

대칭키 암호화

대칭키 암호화는 같은 키를 사용하여 데이터를 암호화 및 복호화하는 기술입니다. Go 언어에서는 crypto/cipher 패키지를 사용하여 대칭키 암호화를 구현할 수 있습니다.

import (
	"crypto/aes"
	"crypto/cipher"
	"crypto/rand"
	"fmt"
	"io"
)

func main() {
	key := []byte("example key 1234")
	plaintext := []byte("Hello, AES!")

	block, err := aes.NewCipher(key)
	if err != nil {
		panic(err.Error())
	}

	ciphertext := make([]byte, aes.BlockSize+len(plaintext))
	iv := ciphertext[:aes.BlockSize]
	if _, err := io.ReadFull(rand.Reader, iv); err != nil {
		panic(err.Error())
	}

	stream := cipher.NewCFBEncrypter(block, iv)
	stream.XORKeyStream(ciphertext[aes.BlockSize:], plaintext)

	fmt.Printf("%x\n", ciphertext)
}

비대칭키 암호화

비대칭키 암호화는 공개키와 개인키를 사용하여 데이터를 암호화하고 복호화하는 기술입니다. Go 언어에서는 crypto/rsa 패키지를 사용하여 비대칭키 암호화를 구현할 수 있습니다.

import (
	"crypto/rand"
	"crypto/rsa"
	"crypto/x509"
	"encoding/pem"
	"fmt"
)

func main() {
	privKey, err := rsa.GenerateKey(rand.Reader, 2048)
	if err != nil {
		panic(err.Error())
	}

	pubKey := &privKey.PublicKey

	plaintext := []byte("Hello, RSA!")
	ciphertext, err := rsa.EncryptPKCS1v15(rand.Reader, pubKey, plaintext)
	if err != nil {
		panic(err.Error())
	}

	fmt.Printf("%x\n", ciphertext)
}

인증 및 디지털 서명

Go 언어에서는 crypto 패키지를 사용하여 인증 및 디지털 서명을 구현할 수 있습니다. 디지털 서명은 데이터의 무결성 및 인증을 검증하는 데 사용됩니다.

import (
	"crypto"
	"crypto/rand"
	"crypto/rsa"
	"crypto/sha256"
	"fmt"
)

func main() {
	privKey, err := rsa.GenerateKey(rand.Reader, 2048)
	if err != nil {
		panic(err.Error())
	}

	message := []byte("Hello, digital signature!")
	hashed := sha256.Sum256(message)
	signature, err := rsa.SignPKCS1v15(rand.Reader, privKey, crypto.SHA256, hashed[:])
	if err != nil {
		panic(err.Error())
	}

	fmt.Printf("%x", signature)
}

위의 예제들은 Go 언어에서의 암호화 기능을 보여주는 간단한 예시입니다. Go 언어의 암호화 기능은 데이터 보호 및 보안 통신에 필수적인 도구를 제공합니다.

참고문헌: Go 언어 공식 문서