Go言語 OpenSSLの使い方:基本手順とサンプルコード
Go言語でOpenSSLライブラリを使用する場合、C言語のインターフェースを呼び出すことで実現できます。まず、CGOツールをインストールし、GoコードでC言語のヘッダーファイルとライブラリファイルをインポートし、それから適切なOpenSSL関数をGoコードで呼び出せばよいです。
以下は、Go言語でOpenSSLライブラリを使用して暗号化操作を行う方法を示す単純なサンプルコードです。
package main
/*
#cgo LDFLAGS: -lssl -lcrypto
#include <openssl/aes.h>
#include <openssl/rand.h>
#include <openssl/evp.h>
#include <openssl/sha.h>
*/
import "C"
import (
"fmt"
"unsafe"
)
func main() {
key := make([]byte, 32)
C.RAND_bytes((*C.uchar)(unsafe.Pointer(&key[0])), C.int(len(key)))
text := []byte("hello world")
encrypted := make([]byte, len(text))
iv := make([]byte, C.EVP_MAX_IV_LENGTH)
C.EVP_CIPHER_CTX_new()
ctx := C.EVP_CIPHER_CTX_new()
C.EVP_EncryptInit_ex(ctx, C.EVP_aes_256_cbc(), nil, (*C.uchar)(unsafe.Pointer(&key[0])), (*C.uchar)(unsafe.Pointer(&iv[0])))
C.EVP_EncryptUpdate(ctx, (*C.uchar)(unsafe.Pointer(&encrypted[0])), (*C.int)(unsafe.Pointer(C.int(len(encrypted)))), (*C.uchar)(unsafe.Pointer(&text[0])), C.int(len(text)))
fmt.Printf("Encrypted: %x\n", encrypted)
decrypted := make([]byte, len(text))
C.EVP_DecryptInit_ex(ctx, C.EVP_aes_256_cbc(), nil, (*C.uchar)(unsafe.Pointer(&key[0])), (*C.uchar)(unsafe.Pointer(&iv[0])))
C.EVP_DecryptUpdate(ctx, (*C.uchar)(unsafe.Pointer(&decrypted[0])), (*C.int)(unsafe.Pointer(C.int(len(decrypted))), (*C.uchar)(unsafe.Pointer(&encrypted[0])), C.int(len(encrypted)))
fmt.Printf("Decrypted: %s\n", decrypted)
}
注意:これは単なる簡単なサンプルコードであり、完全なものではありません。実際のプロジェクトでは、より詳細なドキュメントやサンプルコードを使用して、OpenSSLライブラリの正しい使い方を学ぶことをお勧めします。