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

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

This is the code I use in 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 in the line above ^.

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

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

I believe that there is nothing wrong with the key combination, as I get an error message before even trying to decrypt something. The privateKey parameter is currently hard-coded into a script using this format:

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

So, it seems to me that the footer is really included in the line ... I debugged and searched everywhere, but I cannot solve the problem. I am new to RSA & Bouncycastle, so maybe I am using the wrong methods.

I hope you help, thanks! - G4A

PS This is my first question on Stackoverflow, I just created an account, so if you could also give me some feedback on how I formulated this question; great!

+6
source share
2 answers

You need to add a new line between the prefix connex and the Base64 data, therefore:

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

This is because the pem specification allows you to use other text headers between them.

+8
source

If this does not 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-----"

0
source

Source: https://habr.com/ru/post/1234363/


All Articles