我试图在C#中签名一些字节,这要归功于类RSACryptoServiceProvider,并在C++中使用Crypto++库进行验证。尽管我尝试了所有的尝试,但验证失败,尽管我确信我的密钥和签名。c#中的RSA签名和Crypto ++的C++验证
在C#中我签如下:
CspParameters parameters = new CspParameters();
parameters.KeyNumber = (int)KeyNumber.Signature;
using (RSACryptoServiceProvider rsa = new RSACryptoServiceProvider(1024, parameters))
{
privateKeyInfo = rsa.ExportParameters(true);
publicKeyInfo = rsa.ExportParameters(false);
}
在C++中,我创建了公共密钥,并尝试验证如下:
var message = "hello";
var bytes = System.Text.Encoding.UTF8.GetBytes(message);
byte[] signedHash;
using (RSACryptoServiceProvider rsa = new RSACryptoServiceProvider())
{
// Import the key information.
rsa.ImportParameters(privateKey);
// Sign the data, using SHA256 as the hashing algorithm
signedHash = rsa.SignData(bytes, CryptoConfig.MapNameToOID("SHA256"));
}
我的密钥如下生成
RSA::PublicKey publicKey;
byte signature[128];
signature[0]= 150;
//....fill up to 127 , corresponds to "signedHash" variable from c# code
signature[127]= 89;
string simplemessage = "hello";
string modulus = "0Z8GUI/rxlXanCCjkiP+c9HyvdlOibst2YD5XmZk4F86aLr7LbLtI7FMnr6rcQZa6RXkAykb5MIbasmkOmkLzSjhdTThnaZyuKBOBoybYB5mDecF2VMXfUIryEBFn4i6y58qhy0BnDnIhucdNXX0px10HL3uYzR2KBTC0lSFFmE=";
string exponent = "AQAB";
char modulusCharred[1024];
strncpy_s(modulusCharred, base64ToHex(modulus).c_str(), sizeof(modulusCharred));
modulusCharred[sizeof(modulusCharred) - 1] = 0;
char exponentCharred[1024];
strncpy_s(exponentCharred, base64ToHex(exponent).c_str(), sizeof(exponentCharred));
exponentCharred[sizeof(exponentCharred) - 1] = 0;
Integer n(modulusCharred);
Integer e(exponentCharred);
publicKey.Initialize(n, e);
AutoSeededRandomPool rnd;
if(!publicKey.Validate(rnd, 3))
throw runtime_error("Rsa public key validation failed"); // no error is thrown
RSASS<PSS, SHA256>::Verifier verifier(publicKey);
bool result = verifier.VerifyMessage((const byte*)simplemessage.c_str(),simplemessage.length(), signature,128);
if(true == result) {
cout << "Signature on message verified" << endl;
} else {
cout << "Message verification failed" << endl; // always fail...
}
模数和指数是从c#中使用rsa.ToXmlString(false)获得的XML中的复制/过去。该功能base64toHex
由下式给出(在另一个SO后发现):
std::string base64ToHex(std::string base64String)
{
std::string decodedString, finalString;
CryptoPP::StringSource river(base64String, true,
new CryptoPP::Base64Decoder(new CryptoPP::StringSink(decodedString)));
CryptoPP::StringSource stream(decodedString, true,
new CryptoPP::HexEncoder(new CryptoPP::StringSink(finalString)));
finalString.erase(std::remove(finalString.begin(), finalString.end(), '\n'), finalString.end());
return finalString;
}
我不想使用任何外部文件,仅字节(或字符串)变量。另外我不确定我定义我的验证器的方式:RSASS<PSS, SHA256>::Verifier
。
你能帮我解决吗?
RSACryptoServiceProvider只做PKCS1_v1.5签名,它不能做PSS。所以你需要使用PKCS验证器。 – bartonjs
谢谢,我已将我的验证器修改为'RSASS ::验证器',但问题仍然存在。 –
Malick