在golang中使用cgo调用openssl库的md5方法,使用MD5_Init, MD5_Update, MD5_Final.
package main
/*
#cgo CFLAGS: -I ./include
#cgo LDFLAGS: -L ./lib -lcrypto
#include <stdlib.h>
#include <openssl/md5.h>
*/
import "C"
import (
"encoding/hex"
"fmt"
"strings"
"unsafe"
)
func main() {
var ctx C.MD5_CTX
C.MD5_Init(&ctx)
data := []byte("https://const.net.cn")
C.MD5_Update(&ctx, unsafe.Pointer(&data[0]), C.size_t(len(data)))
md := make([]byte, 16)
C.MD5_Final((*C.uchar)(unsafe.Pointer(&md[0])), &ctx)
md5Str := hex.EncodeToString(md)
md5Str = strings.ToUpper(md5Str)
fmt.Printf("md5Str = %s\n", md5Str)
}
输出:
go run .
md5Str = 682D2C63236AF6E721794B2988FC1D44
echo -n "https://const.net.cn" | md5sum
682d2c63236af6e721794b2988fc1d44 -