C#中的RSA签名以及使用Crypto ++在C ++中进行验证 [英] RSA signature in c# and verification in C++ with Crypto++

查看:200
本文介绍了C#中的RSA签名以及使用Crypto ++在C ++中进行验证的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

由于使用类 RSACryptoServiceProvider ,并使用 Crypto ++ 库。尽管进行了所有尝试,但尽管我确定自己的密钥和签名仍无法通过验证。

I'm trying to sign some bytes in C# thanks to the class RSACryptoServiceProvider and to verify it in C++ with the Crypto++ library. Despite all my attempts, the validation fail although I'm sure of my key and signature.

在C#中,我按照以下方式签名:

In C# I sign as follow :

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"));
}

我的密钥生成如下:

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 ++中,我创建了公共密钥,并尝试如下进行验证:

In C++, I create the public key and try to verify it as follow :

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...
}

模量和指数是从使用 rsa.ToXmlString(false)。函数 base64toHex 由(在另一个SO帖子上找到)给出:

Modulus and exponent are copy/past from the xml obtained in c# using rsa.ToXmlString(false). The function base64toHex is given by (found on another SO post):

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

I do not want to use any external files, only bytes (or string) variable. Also I'm not sure of the way I define my verifier : RSASS<PSS, SHA256>::Verifier.

您能帮我吗?

推荐答案


此答案适用于crypto ++和Windows API。

This answer is for both crypto++ and the windows API.

经过多次尝试/错误,我终于成功了,问题来自我构建crypto ++ rsa密钥的方式( Integer 类型:模数和指数)。

After a lot of trials/errors I finally succeed, the problem came from the way I built the crypto++ rsa keys ( Integer type : modulus and exponent).

创建了一个新函数 GetIntegerFromBase64String 直接将我们从 rsa.ToXmlString 的xml输出获得的模量和指数直接转换为

I have created a new function GetIntegerFromBase64String that convert directly the modulus and exponent we obtain from the xml output of rsa.ToXmlString to the Integer type to initialize key in cryptopp.

完全加密++示例:

        string signature_64str = "G+PQaArLByTNYF5c5BZo2X3Guf1AplyJyik6NXCJmXnZ7CD5AC/OKq+Iswcv8GboUVsMTvl8G+lCa9Od0DfytnDui7kA/c1qtH7BZzF55yA5Yf9DGOfD1RHOl3OkRvpK/mF+Sf8nJwgxsg51C3pk/oBFjA450q2zq8HfFG2KJcs=";  
        string modulus_64str = "0Z8GUI/rxlXanCCjkiP+c9HyvdlOibst2YD5XmZk4F86aLr7LbLtI7FMnr6rcQZa6RXkAykb5MIbasmkOmkLzSjhdTThnaZyuKBOBoybYB5mDecF2VMXfUIryEBFn4i6y58qhy0BnDnIhucdNXX0px10HL3uYzR2KBTC0lSFFmE=";
        string exponent_64str  = "AQAB";

        Integer mod_integer = GetIntegerFromBase64String(modulus_64str);
        Integer pub_integer = GetIntegerFromBase64String(exponent_64str);
        InvertibleRSAFunction param;
        param.SetModulus(mod_integer);
        param.SetPublicExponent(pub_integer);
        RSA::PublicKey pubkey(param);

        string decoded_sig = DecodeBase64String(signature_64str);


        if(!pubkey.Validate(rnd, 3))
                cout << "Rsa public key validation failed" << endl;
        else
               cout << " key validation success"<<  endl;


        RSASS<PKCS1v15, SHA512>::Verifier verif(pubkey);
        bool res = verif.VerifyMessage( reinterpret_cast<const byte*>(message.c_str()), message.length(), reinterpret_cast<const byte*>(decoded_sig.c_str()), decoded_sig.length() );

         if( res ) {
                    cout << "Signature on message verified " << endl;
         } else {
                    cout << "Message verification failed " << endl;
         }

with:

string DecodeBase64String(string encoded )
{
        string decoded;    
        Base64Decoder decoder;
        decoder.Attach( new StringSink( decoded ) );
        decoder.Put( (byte*)encoded.data(), encoded.size() );
        decoder.MessageEnd();
        return decoded;

}
 Integer GetIntegerFromBase64String(string encoded)
{
        string decoded = DecodeBase64String(encoded);              
        Integer integer( (byte*)decoded.c_str(),decoded.length());
        return integer;
}






此外,我已转载使用Windows API进行验证,在这种情况下,我不使用xml密钥,而是直接使用从 rsa.ExportCspBlob(false)

全Windows api示例:

在c#中,我得到的CspBlob如下:

In c# I got the CspBlob as follow :

  using (RSACryptoServiceProvider rsa = new RSACryptoServiceProvider())
            {
                rsa.ImportParameters(privateKey);
                var cspBlob = rsa.ExportCspBlob(false);
                var cspBlobBase_64str = Convert.ToBase64String(cspBlob);// <---- HERE

然后在c ++中,我加载blob并按照以下步骤验证签名:

Then in c++, I load the blob and verify the signature as follow :

#include <windows.h>
...
            string ErrorMessage;
            string signature_64str = "G+PQaArLByTNYF5c5BZo2X3Guf1AplyJyik6NXCJmXnZ7CD5AC/OKq+Iswcv8GboUVsMTvl8G+lCa9Od0DfytnDui7kA/c1qtH7BZzF55yA5Yf9DGOfD1RHOl3OkRvpK/mF+Sf8nJwgxsg51C3pk/oBFjA450q2zq8HfFG2KJcs=";
            string public_key_blob_64_bit_encoded = "BgIAAACkAABSU0ExAAQAAAEAAQBhFoVU0sIUKHY0Y+69HHQdp/R1NR3nhsg5nAEthyqfy7qIn0VAyCtCfRdT2QXnDWYeYJuMBk6guHKmneE0deEozQtpOqTJahvC5BspA+QV6VoGcau+nkyxI+2yLfu6aDpf4GRmXvmA2S27iU7ZvfLRc/4jkqMgnNpVxuuPUAaf0Q==";
            string message = "hello";


            if( RSA_VerifySignature(message,   signature_64str, public_key_blob_64_bit_encoded,  ErrorMessage))
            {
                 cout << "OK : Signature on message verified " << endl;
            }
            else
            {
                 cout << "Message verification failed, Error : " << ErrorMessage << endl;
            }

with:

 bool RSA_VerifySignature(string message, string signature_64BitEncoded, string publickeyBlob_64BitEncoded, string &ErrorMessage)
{
     const size_t LENGHT_SIGNATURE = 128; // 128 bytes == 1024 RSA Key bits 
     const size_t LENGHT_BLOB_PUBLIC_KEY = 148; // 148 bytes 

     bool isSigOk = false;
     HCRYPTHASH hash;

     byte  decoded_Blob[LENGHT_BLOB_PUBLIC_KEY] ;
     size_t size_pubkey = Base64Decode(publickeyBlob_64BitEncoded, decoded_Blob, LENGHT_BLOB_PUBLIC_KEY);

     byte  decoded_signature[LENGHT_SIGNATURE] ;
     size_t size_signature =Base64Decode(signature_64BitEncoded, decoded_signature, LENGHT_SIGNATURE);

     //reverse bytes
     byte reverse_decoded_signature[LENGHT_SIGNATURE];
     for(int i=0;i<sizeof(reverse_decoded_signature);i++)
         reverse_decoded_signature[i] = decoded_signature[LENGHT_SIGNATURE-i-1];


     HCRYPTPROV cryptProvider;
     // Get a handle to the PROV_RSA_AES (for CALG_SHA_512).
     if (!CryptAcquireContext(&cryptProvider, 0, 0, PROV_RSA_AES, CRYPT_VERIFYCONTEXT)){  
        ErrorMessage = "Failure to acquire context";
        goto Exit;
     }

     HCRYPTKEY publicKeyc;
     // convert the blob to the public key
     if(!CryptImportKey(cryptProvider, decoded_Blob, LENGHT_BLOB_PUBLIC_KEY, 0, 0, &publicKeyc)){ 

        ErrorMessage = "Failure to import key";
        goto Exit;
     }

     // create the hash object
     if(!CryptCreateHash(cryptProvider, CALG_SHA_512 , 0, 0, &hash)){
        ErrorMessage = "Failure to creat Hash"  ;
        goto Exit;
     }

     //hash the message
     if(!CryptHashData(hash, (byte*) message.c_str(), message.length(), 0)){  
        ErrorMessage = "Failure to Hash Data"  ;
        goto Exit;
     }

       isSigOk = CryptVerifySignature(hash, reverse_decoded_signature, sizeof(reverse_decoded_signature), publicKeyc, nullptr, 0);

       if(!isSigOk) ErrorMessage = "Invalid Signature"  ;


     Exit:  
     // After processing, hHash and cryptProvider must be released. 
     if(hash) 
        CryptDestroyHash(hash);
     if(cryptProvider) 
        CryptReleaseContext(cryptProvider,0);
       return isSigOk;
}

其中有 Base64Decode 来自 SO答案

ps:请注意,我在此答案中已切换到SHA512。

ps: note that I have switched to SHA512 in this answer .

这篇关于C#中的RSA签名以及使用Crypto ++在C ++中进行验证的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆