1

Ok, I have a string of text, encoded in Base64.

I want to decode this from Base64 to a byte array, then decrypt this with my private key. My private key is a *.pem file. I am lost!

I think I need to declare a byte array, grab the text between the ---BEGIN--- and ---END--- part of my *.pem, and convert this from a base 64 string as the result of my byte array.

I then need to declare an X509Certificate2, and use the constructor that takes a byte array and a string of text, the byte array being my private key, the string of text being my passphrase like below:

byte[] myprivateKey = Convert.FromBase64String("BASE 64 ENCODED PRIVATE KEY GOES HERE");
X509Certificate2 myPem = new X509Certificate2(myprivateKey, "MY PASSPHRASE");

However, I am getting the following error at this point:

Cannot find the requested object.

Am I heading in the right direction at least or am I way off? What do I need to do here?

poupou
  • 43,413
  • 6
  • 77
  • 174
JMK
  • 27,273
  • 52
  • 163
  • 280

1 Answers1

1

X509Certificate2 won't read a private key from a PEM base64-encoded file. You'll need to read the private key apart from the certificate and then assign it the the PrivateKey property.

See how to get private key from PEM file? for more details.

Community
  • 1
  • 1
poupou
  • 43,413
  • 6
  • 77
  • 174
  • Thankyou, this is really helpful, however where do I find "ASN1" and "X509ExtensionCollection"? As in which references do I need to use? Thankyou – JMK Dec 23 '11 at 14:12
  • This is all part of Mono.Security.dll (which is part of Mono but works with MS.NET too). Full source code is available from https://github.com/mono/mono/tree/master/mcs/class/Mono.Security – poupou Dec 23 '11 at 14:27
  • Sorry I have one more question, is there an actual DLL file that I can download and add to my project? Or do I need to download the project at this link and add this? Thankyou – JMK Dec 23 '11 at 15:25
  • AFAIK the binary .dll is not downloadable by itself. But it does exists in all the Mono runtime downloads for Win32 (and inside other projects that re-use it). Otherwise you can copy-paste the sources/files that you require in your own application. – poupou Dec 23 '11 at 15:44