From ba96fa1c66e27da3f30ed55b4c54f4bf609574aa Mon Sep 17 00:00:00 2001 From: Daiki Ueno Date: Mon, 16 Oct 2023 12:50:06 +0900 Subject: [PATCH] rsa: skip setting label for RSA OAEP if empty The label parameter for RSA OAEP is optional and by default it should be empty. Given that it is set only once in setupEVP, we can bypass the call to EVP_PKEY_CTX_set0_rsa_oaep_label if the label is empty to spare 1-byte memory allocation and the following CGO call. Signed-off-by: Daiki Ueno --- evp.go | 34 ++++++++++++++-------------------- 1 file changed, 14 insertions(+), 20 deletions(-) diff --git a/evp.go b/evp.go index 3775fa42..68adf7cd 100644 --- a/evp.go +++ b/evp.go @@ -209,29 +209,23 @@ func setupEVP(withKey withKeyFunc, padding C.int, if len(label) > 0 { clabel = (*C.uchar)(cryptoMalloc(len(label))) copy((*[1 << 30]byte)(unsafe.Pointer(clabel))[:len(label)], label) - } - var err error - if vMajor == 3 { - // Docs say EVP_PKEY_CTX_set0_rsa_oaep_label accepts a null label, - // but it does not: https://github.com/openssl/openssl/issues/21288 - if len(label) == 0 { - // cryptoMalloc can't create a zero-length array: use size 1. - clabel = (*C.uchar)(cryptoMalloc(1)) - } - ret := C.go_openssl_EVP_PKEY_CTX_set0_rsa_oaep_label(ctx, unsafe.Pointer(clabel), C.int(len(label))) - if ret != 1 { - err = newOpenSSLError("EVP_PKEY_CTX_set0_rsa_oaep_label failed") + var err error + if vMajor == 3 { + ret := C.go_openssl_EVP_PKEY_CTX_set0_rsa_oaep_label(ctx, unsafe.Pointer(clabel), C.int(len(label))) + if ret != 1 { + err = newOpenSSLError("EVP_PKEY_CTX_set0_rsa_oaep_label failed") + } + } else { + ret := C.go_openssl_EVP_PKEY_CTX_ctrl(ctx, C.GO_EVP_PKEY_RSA, -1, C.GO_EVP_PKEY_CTRL_RSA_OAEP_LABEL, C.int(len(label)), unsafe.Pointer(clabel)) + if ret != 1 { + err = newOpenSSLError("EVP_PKEY_CTX_ctrl failed") + } } - } else { - ret := C.go_openssl_EVP_PKEY_CTX_ctrl(ctx, C.GO_EVP_PKEY_RSA, -1, C.GO_EVP_PKEY_CTRL_RSA_OAEP_LABEL, C.int(len(label)), unsafe.Pointer(clabel)) - if ret != 1 { - err = newOpenSSLError("EVP_PKEY_CTX_ctrl failed") + if err != nil { + cryptoFree(unsafe.Pointer(clabel)) + return nil, err } } - if err != nil { - cryptoFree(unsafe.Pointer(clabel)) - return nil, err - } case C.GO_RSA_PKCS1_PSS_PADDING: md := cryptoHashToMD(ch) if md == nil {