Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Cache HMAC object and fix memory leak #77

Merged
merged 1 commit into from
Jun 16, 2023
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
18 changes: 14 additions & 4 deletions hmac.go
Original file line number Diff line number Diff line change
Expand Up @@ -8,12 +8,15 @@ import "C"
import (
"hash"
"runtime"
"sync"
"unsafe"
)

var paramDigest = C.CString("digest")

var (
paramAlgHMAC = C.CString("HMAC")
paramDigest = C.CString("digest")
fetchHMACOnce sync.Once
evpHMAC C.GO_EVP_MAC_PTR
)

// NewHMAC returns a new HMAC using OpenSSL.
Expand Down Expand Up @@ -83,8 +86,15 @@ func newHMAC1(key []byte, h hash.Hash, md C.GO_EVP_MD_PTR) *opensslHMAC {
}

func newHMAC3(key []byte, h hash.Hash, md C.GO_EVP_MD_PTR) *opensslHMAC {
mac := C.go_openssl_EVP_MAC_fetch(nil, paramAlgHMAC, nil)
ctx := C.go_openssl_EVP_MAC_CTX_new(mac)
fetchHMACOnce.Do(func() {
name := C.CString("HMAC")
evpHMAC = C.go_openssl_EVP_MAC_fetch(nil, name, nil)
C.free(unsafe.Pointer(name))
})
if evpHMAC == nil {
panic("openssl: HMAC not supported")
}
ctx := C.go_openssl_EVP_MAC_CTX_new(evpHMAC)
if ctx == nil {
panic("openssl: EVP_MAC_CTX_new failed")
}
Expand Down