0

I created a service to decrypt some data. I'm using placeholder/static data and my service looks like this at the moment.

public class DecryptionService
{
    string privateKeyPem = @"-----BEGIN RSA PRIVATE KEY-----
MIIBOgIBAAJBAKj34GkxFhD90vcNLYLInFEX6Ppy1tPf9Cnzj4p4WGeKLs1Pt8Qu
KUpRKfFLfRYC9AIKjbJTWit+CqvjWYzvQwECAwEAAQJAIJLixBy2qpFoS4DSmoEm
o3qGy0t6z09AIJtH+5OeRV1be+N4cDYJKffGzDa88vQENZiRm0GRq6a+HPGQMd2k
TQIhAKMSvzIBnni7ot/OSie2TmJLY4SwTQAevXysE2RbFDYdAiEBCUEaRQnMnbp7
9mxDXDf6AU0cN/RPBjb9qSHDcWZHGzUCIG2Es59z8ugGrDY+pxLQnwfotadxd+Uy
v/Ow5T0q5gIJAiEAyS4RaI9YG8EWx/2w0T67ZUVAw8eOMB6BIUg0Xcu+3okCIBOs
/5OiPgoTdSy7bcF9IGpSE8ZgGKzgYQVZeN97YE00
-----END RSA PRIVATE KEY-----";

    private async Task Decrypt(byte[] encryptedBytes)
    {
        // Decrypt the data
        RSA rsa = RSA.Create();
        rsa.ImportFromPem(privateKeyPem);

        // Decrypt the encrypted bytes using the private key
        // TODO
    }
}

Now, this crashes really fast on ImportFromPem stating Key is not a valid public or private key.

Is not the string formatted correctly? Am I missing some padding?

u314
  • 87
  • 1
  • 7
  • What is the exact exception? – Neil Aug 25 '23 at 20:40
  • 1
    With this formatting, your key contains extra line feeds. – Alexander Petrov Aug 25 '23 at 21:31
  • Agree with @AlexanderPetrov get rid of those line feeds in that `@"` there and make it one LONG one or concat them as strings together.... – Mark Schultheiss Aug 25 '23 at 21:33
  • @AlexanderPetrov I tried to add privateKeyPem = privateKeyPem.Replace("\r\n", "\n"); but it did not help – u314 Aug 25 '23 at 22:11
  • See https://stackoverflow.com/a/53439332/238704. – President James K. Polk Aug 26 '23 at 01:07
  • 2
    Your private key is a PEM encoded key in PKCS#1 format, which can be imported by [`ImportFromPem()`](https://learn.microsoft.com/en-us/dotnet/api/system.security.cryptography.rsa.importfrompem?view=net-7.0#remarks) (besides the PKCS#8 format). Format and encoding are fine, I can't reproduce the problem either, see online https://dotnetfiddle.net/8iBj64. Check if there are not hidden white spaces of any kind. Also you should specify platform and .NET version. – Topaco Aug 26 '23 at 06:09
  • 1
    You can also follow the suggestion of President James K. Polk and use `ImportRSAPrivateKey()` which imports a private DER encoded PKCS#1 key. For this you have to convert your PEM key into a DER key (removing header, footer and linebreaks and Base64 decoding the rest). But as I said `ImportFromPem()` should actually work and do the manual conversion from PEM to DER for you. – Topaco Aug 26 '23 at 06:17

0 Answers0