在golang中使用cgo调用openssl库的md5方法,不使用var定义,使用new来定义C.MD5_CTX

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() {
    ctx := new(C.MD5_CTX)
    C.MD5_Init(ctx)
    data := []byte("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 = FA8424A7B72EB90BF04685205ECC5760
echo -n "const.net.cn" | md5sum
fa8424a7b72eb90bf04685205ecc5760 -

本文链接地址:https://const.net.cn/43.html

标签: none

添加新评论