Using OpenSSL in Go

In Go language, using the OpenSSL library can be achieved by invoking C language interfaces. Initially, you need to install the CGO tool, import C language header and library files in the Go code, and then call the corresponding OpenSSL functions in the Go code.

Here is a simple example code demonstrating how to perform encryption operations using the OpenSSL library in the Go language.

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)
}

Please note that this is just a simple example code and not complete. For actual projects, it is recommended to learn how to correctly use the OpenSSL library through more detailed documentation and example codes.

bannerAds