Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

System.IO.IOException: -----END RSA PRIVATE KEY not found

I am trying to create an online database application using PHP for the server and C# form application for the client. On the server I encrypt a simple string using a public RSA key with the PHPSecLib. Then the C# application receives the string and tries to decrypt it using the corresponding private key. The bytes are base64 encoded on the server and decoded to bytes again by C#. I created the key pair using the PHPSecLib.

This is the code I use on the client application:

public string rsa_decrypt(string encryptedText, string privateKey) {
        byte[] bytesToDecrypt = Convert.FromBase64String(encryptedText);
        Pkcs1Encoding decrypter = new Pkcs1Encoding(new RsaEngine());
        //the error occurs on this line:
        AsymmetricCipherKeyPair RSAParams = (AsymmetricCipherKeyPair)new PemReader(new StringReader(privateKey)).ReadObject();

        decrypter.Init(false, RSAParams.Private);
        byte[] decryptedBytes = decrypter.ProcessBlock(bytesToDecrypt, 0, bytesToDecrypt.Length);
        string decryptedString = Convert.ToBase64String(decryptedBytes);
        return decryptedString;
    }

But, I get the following error on the line specified above^.

An unhandled exception of type 'System.IO.IOException' occurred in BouncyCastle.Crypto.dll

Additional information: -----END RSA PRIVATE KEY not found

I believe there's nothing wrong with the key pair combo as I get an error before I even try to decrypt anything. The privateKey parameter is currently hardcoded into the script using this format:

string privateKey = "-----BEGIN RSA PRIVATE KEY-----XXXXXXXX-----END RSA PRIVATE KEY-----";

So it seems to me the footer actually is included in the string... I have debugged and googled everywhere but I can't seem to solve it. I'm pretty new to RSA&Bouncycastle so maybe I'm just using wrong methods.

Hope you can help, thanks! - G4A

P.S. This is my first Stackoverflow question, I just created an account, so if you could also give me some feedback on the way I formulated this question; great!

like image 525
G4A Avatar asked Oct 23 '15 11:10

G4A


2 Answers

You need to add a new line between the pre/post encapsulation boundary text and the Base64 data, so:

 string privateKey = "-----BEGIN RSA PRIVATE KEY-----\r\nXXX\r\n-----END RSA PRIVATE KEY-----";

This is because the pem specification allows for the existence of other textual headers between the two.

like image 106
Alex K. Avatar answered Sep 28 '22 07:09

Alex K.


If this doesn't work "-----BEGIN RSA PRIVATE KEY-----\r\nXXXXXXXX\r\n-----END RSA PRIVATE KEY-----"

please try this "-----BEGIN RSA PRIVATE KEY-----
XXXXXXXX
-----END RSA PRIVATE KEY-----"

like image 23
Alessandro Alves Avatar answered Sep 28 '22 06:09

Alessandro Alves