openSSL:如何使用解码密钥初始化EVP_PKEY对象
openSSL: How to initialize EVP_PKEY object with the decoded key?
我有以下一段代码:
void Impl::sign()
{
assert(!canonicalMessage_.empty());
char* key = b64Decode(secureKey_);
EVP_PKEY* pKey = NULL;
EVP_MD_CTX* mdctx = NULL;
std::size_t* slen = NULL;
unsigned char** sig = NULL;
*sig = NULL;
// Create the Message Digest Context
mdctx = EVP_MD_CTX_create();
// Initialize the DigestSign operation.
EVP_DigestSignInit(mdctx, NULL, EVP_sha256(), NULL, pKey);
// Call update with the message
const char* msg = canonicalMessage_.c_str();
EVP_DigestSignUpdate(mdctx, msg, strlen(msg));
// Obtain the length of the signature.
EVP_DigestSignFinal(mdctx, NULL, slen);
// Allocate memory for the signature based on size in slen
*sig = (unsigned char*)OPENSSL_malloc(sizeof(unsigned char) * (*slen));
// Obtain the signature
EVP_DigestSignFinal(mdctx, *sig, slen);
/* Clean up */
if (*sig) OPENSSL_free(*sig);
if(mdctx) EVP_MD_CTX_destroy(mdctx);
}
在这里,我使用内部函数获得解码密钥b64Decode()
(定义无关紧要)。我的问题是如何将pKey
(由key
初始化)传递给EVP_DigestSignInit
函数。我找到了与此相关的链接(openSSL:如何初始化公钥加密的密钥?),但与我的情况不同,这里使用了文件。
实际上,我通过下载此处指定的源代码找到了解决方案:https://wiki.openssl.org/index.php/EVP_Signing_and_Verifying
溶液:
unsigned char* key = b64Decode(secureKey_);
const EVP_MD* md = EVP_get_digestbyname("sha256");
EVP_PKEY* pKey = EVP_PKEY_new_mac_key(EVP_PKEY_HMAC, NULL, key, EVP_MD_size(md));