問題: 數字簽名時,不同的輸入,部分輸入驗證會失敗,部分輸入驗證成功,(感覺是數字簽名的長度問題),請問下是什么原因導致的呢,該如何解決呢,使用的 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);
}
uj5u.com熱心網友回復:
https://www.kancloud.cn/kancloud/rsa_algorithm/48484轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/284817.html
標籤:其它技術問題
下一篇:大佬們求救c++