Search code examples
c#c++encryption-asymmetric

Porting code from c++ to c# - Encrypting with RSA PKCS#1 private key


I'm trying to port this piece of code from c++ to c#:

...
strPrivateKey = "someBase64EncodedPrivateKey";
long sizeKey = DecodeBase64(strPrivateKey, pKey);
const unsigned char* _pKey = pKey;
d2i_RSAPrivateKey(&pRSA, &_pKey, sizeKey);
...

RSA_private_encrypt(sizeOfMessage, pMessage, pSignature, pRSA, RSA_PKCS1_PADDING);

...

So far here is my code:

var strPrivateKey = "someBase64EncodedPrivateKey";
var bytes = Convert.FromBase64String(strPrivateKey);

var rsa = new RSACryptoServiceProvider();

// How to set the private key to the rsa object?!

byte[] someDataToEncrypt = /* Set the data to encrypt */;
var encryptedData = rsa.Encrypt(someDataToEncrypt, false);

EDIT: I'm not ever sure if it's the class I should refer to.

Thanks


Solution

  • Fixed it by adding:

    At the begin of the private key: "-----BEGIN RSA PRIVATE KEY-----\r\n"
    After each line of my private key : "\r\n"
    At the end of my private key: "-----END RSA PRIVATE KEY-----"
    

    And finally, I used OpenSsl.NET as library. This post originally solved my problem: Decrypting RSA using OpenSSL.NET with Existing Key