【发布时间】:2015-03-13 08:20:01
【问题描述】:
经过几天的互联网搜索和 openssl 文档的搜索,我遇到了困难。我正在尝试使用私钥对消息进行签名,然后使用公钥验证消息的真实性。
密钥生成代码:
//Generate RSA Keys
EVP_PKEY_CTX* KeyCtx = EVP_PKEY_CTX_new_id(EVP_PKEY_RSA, NULL);
if (KeyCtx == nullptr)
return false;
if (EVP_PKEY_keygen_init(KeyCtx) <= 0)
return false;
if (EVP_PKEY_CTX_set_rsa_keygen_bits(KeyCtx, RSA_KeyLen) <= 0)
return false;
if (EVP_PKEY_keygen(KeyCtx, &m_ServerKeyPair) <= 0)
return false;
if (EVP_PKEY_keygen(KeyCtx, &m_ClientKeyPair) <= 0)
return false;
//Write Keys to EVP_PKEYS for actual internal encryption,BIO mem is wiped after read so we need a new copy
PEM_read_bio_PrivateKey(KeyToPrivBio(m_ServerKeyPair), &m_ServerPrivateKey, NULL, NULL);
PEM_read_bio_PUBKEY(KeyToPubBio(m_ServerKeyPair), &m_ServerPublicKey, NULL, NULL);
PEM_read_bio_PrivateKey(KeyToPrivBio(m_ClientKeyPair), &m_ClientPrivateKey, NULL, NULL);
PEM_read_bio_PUBKEY(KeyToPubBio(m_ClientKeyPair), &m_ClientPublicKey, NULL, NULL);
RSA 签名:
bool SecureCrypto::RSASign(const unsigned char* Msg, size_t MsgLen,unsigned char** EncMsg, size_t& MsgLenEnc)
{
EVP_PKEY_size(m_ServerPrivateKey);
*EncMsg = (unsigned char*)malloc(EVP_PKEY_size(m_ServerPrivateKey));
if (EVP_SignInit_ex(m_RSASignCtx, EVP_sha1(), 0) <= 0)
{
printf("Failed Init\n");
return false;
}
if (EVP_SignUpdate(m_RSASignCtx, Msg, MsgLen) <= 0)
{
printf("Failed Update\n");
return false;
}
if (EVP_SignFinal(m_RSASignCtx, *EncMsg, &MsgLenEnc, m_ServerPrivateKey) <=0)
{
printf("Failed Final Sign\n");
return false;
}
EVP_MD_CTX_cleanup(m_RSASignCtx);
return true;
}
RSA 验证:
bool SecureCrypto::RSAVerifySignature(const unsigned char* MsgHash, size_t MsgHashLen,unsigned char* Msg, size_t MsgLen)
{
if (EVP_VerifyInit(m_RSAVerifyCtx, EVP_sha1()) <= 0)
{
printf("Failed Verify Init\n");
return false;
}
if (EVP_VerifyUpdate(m_RSAVerifyCtx, Msg, MsgLen) <= 0)
{
printf("Failed Verify \n");
return false;
}
if (EVP_VerifyFinal(m_RSAVerifyCtx, MsgHash, MsgHashLen, m_ServerPublicKey)<=0);
{
printf("Failed Final Verify %s\n",ERR_error_string(ERR_get_error(),NULL));
return false;
}
EVP_MD_CTX_cleanup(m_RSAVerifyCtx);
return true;
}
密钥生成成功,我查看了它创建的密钥,它们似乎是有效的,格式为-----BEGIN PRIVATE KEY-----,一些大素数,-----END PRIVATE KEY-----。签名似乎成功并返回一个哈希值。 EVP_Verify 在最后一步 EVP_VerifyFinal 失败,ERR_error_string 报告:
error:00000000:lib(0):func(0):reason(0)
这显然没有帮助,有人可以指出我可能做错了什么。这是我第一次深入研究 openssl,所以这里可能存在一些大问题。
【问题讨论】:
-
如果
EVP_VerifyFinal()返回0,则表示签名验证失败,不会设置错误码,因为这是函数的正常操作。小于0和等于0的情况应该分别处理。 -
好的,我会改变它,但这里最大的问题是它失败的原因
-
EVP_Sign和EVP_Verify已弃用,不应使用。你现在应该使用EVP_DigestSign。 “经过几天的互联网搜索和 openssl 文档...” - 您还应该访问 EVP Signing and Verifying。这是一个官方的 OpenSSL 示例。它应该与复制/粘贴一起使用。或访问<openssl dir>/apps中的示例应用程序之一。在 wiki 示例之前,我们曾经必须 grep 应用程序目录。
标签: c++ encryption openssl rsa