c++ 引用openssl库进行签名、验证问题

syao_zj 2021-05-23 11:09:00
问题: 数字签名时,不同的输入,部分输入验证会失败,部分输入验证成功,(感觉是数字签名的长度问题),请问下是什么原因导致的呢,该如何解决呢,使用的 SHA1withRSA 签名
执行结果在截图中



string COpenSslApi::signedRSA(const string& sMsg, const string& sPirvateKeyPath, const E_ALGO& eAlgo)
{
BIO *bufio = NULL; //密钥缓存buff
RSA *rsa = NULL; //rsa结构变量
EVP_PKEY *evpKey = NULL; //EVP KEY结构体变量
const EVP_MD* e_algo = nullptr; //摘要算法 支持sha1 md5等,具体参见枚举
EVP_MD_CTX *mdctx = NULL; //摘要上下文变量
unsigned char* pSign = nullptr; //加密后的内容
unsigned int iSignLen= 0; //sign长度
string sSignRet; //返回值

try
{
//入参判断
if (sMsg.empty() || sPirvateKeyPath.empty())
{
cout << "empty msg or keypath" << endl;
goto safe_exit;
}
//打开密钥文件buff
bufio = BIO_new(BIO_s_file());
BIO_read_filename(bufio, sPirvateKeyPath.c_str());
if(bufio == NULL)
{
cout <<"BIO_read_filename error" <<endl;
goto safe_exit;
}
//获取rsa
rsa = PEM_read_bio_RSAPrivateKey(bufio, NULL, NULL, NULL);
if (rsa == NULL)
{
cout << "PEM_read_bio_RSAPrivateKey error" << endl;
goto safe_exit;
}
//evp_key结构变量初始化
evpKey = EVP_PKEY_new();
if (evpKey == NULL)
{
cout << "EVP_PKEY_new error" << endl;
goto safe_exit;
}
//保存RSA结构体到EVP_PKEY结构体
if (EVP_PKEY_set1_RSA(evpKey, rsa) != 1)
{
cout << "EVP_PKEY_set1_RSA error" << endl;
goto safe_exit;
}
//初始化摘要上下文
mdctx = EVP_MD_CTX_new();
if(mdctx == NULL)
{
cout <<"EVP_MD_CTX_new error" <<endl;
goto safe_exit;
}
EVP_MD_CTX_init(mdctx);
switch(eAlgo)
{
case E_SHA1:
e_algo = EVP_sha1();
break;
case E_MD5:
e_algo = EVP_md5();
break;
default:
break;
}
//签名初始化,设置摘要算法
if(!EVP_SignInit_ex(mdctx, e_algo, NULL))
{
cout <<"EVP_SignInit_ex error" <<endl;
goto safe_exit;
}
cout << "input_msg="<< sMsg.c_str() <<"|leng="<< sMsg.length() <<endl;
//计算签名(摘要)Update
if(!EVP_SignUpdate(mdctx, sMsg.c_str() , sMsg.length() ))
{
cout <<"EVP_SignUpdate error" <<endl;
goto safe_exit;
}
//申请内存
iSignLen = EVP_PKEY_size(evpKey);
pSign = (unsigned char*)malloc(iSignLen+1);
memset(pSign, 0, iSignLen+1);
if( pSign == nullptr || iSignLen == 0)
{
cout <<"EVP_SignFinal error" <<endl;
goto safe_exit;
}
cout << "EVP_PKEY.length = " << iSignLen <<endl;
//签名输出
if(!EVP_SignFinal(mdctx,pSign,&iSignLen,evpKey) )
{
cout <<"EVP_SignFinal error" <<endl;
goto safe_exit;
}
cout << "[after sign]signature.size=" << strlen((char*)pSign) <<endl;
sSignRet = (char *)pSign;

safe_exit:
if (mdctx)
{
EVP_MD_CTX_reset(mdctx);
EVP_MD_CTX_free(mdctx);
mdctx = NULL;
}
//EVP_MD_CTX_cleanup(mdctx);
if (bufio)
{
BIO_free_all(bufio);
bufio = NULL;
}
if (rsa)
{
RSA_free(rsa);
rsa = NULL;
}
if (evpKey)
{
EVP_PKEY_free(evpKey);
evpKey = NULL;
}
if (pSign)
{
free(pSign);
pSign = NULL;
}
}
catch(const std::exception& e)
{
std::cout << e.what() << '\n';
}


return std::move(sSignRet);
}

...全文
2463 1 打赏 收藏 转发到动态 举报
写回复
用AI写文章
1 条回复
切换为时间正序
请发表友善的回复…
发表回复
syao_zj 2021-05-23
  • 打赏
  • 举报
回复
https://www.kancloud.cn/kancloud/rsa_algorithm/48484

3,881

社区成员

发帖
与我相关
我的任务
社区描述
C/C++ 其它技术问题
社区管理员
  • 其它技术问题社区
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧