Windows Phone 7 - can not load certificate in C# code

214 views Asked by At

I'm creating app to WP7 which connecting to web server. I have server root certifcate on my app which I need to read in my application to compare the whole certifacte path, ect. Here is my code to read the file:

var resourceStream = Application.GetResourceStream(new Uri("myCert.der", UriKind.Relative)); 
var content = Encoding.UTF8.GetBytes(new StreamReader(resourceStream.Stream).ReadToEnd()); 
X509Certificate cert = new X509Certificate(content);

But in the last line an exception occurs:

[Cryptography_LegacyNetCF_UnknownError] Arguments: 80092009 Debugging resource strings are unavailable. Often the key and arguments provide sufficient information to diagnose the problem. See http://go.microsoft.com/fwlink/?linkid=106663&Version=4.0.50829.0&File=mscorlib.dll&Key=Cryptography_LegacyNetCF_UnknownError

The stack trace:

at System.Security.Cryptography.CryptographicException.ThrowCryptographicException(Int32 hr) at System.Security.Cryptography.X509Certificates.X509Utils._QueryCertBlobType(Byte[] rawData) at System.Security.Cryptography.X509Certificates.X509Certificate.LoadCertificateFromBlob(Byte[] rawData, Object password, X509KeyStorageFlags keyStorageFlags) at System.Security.Cryptography.X509Certificates.X509Certificate..ctor(Byte[] data)

On msdn page http://msdn.microsoft.com/en-us/library/5128sby8(v=vs.95).aspx I read that "ASN.1 DER is the only certificate format supported by this class"

And this is exactly my format.

Do you have any idea, because I think I tested everything without any effect.

The certificate is ok, and loading well on console application.

Do you have any idea, can you help me ?

Thank in advance,

1

There are 1 answers

0
Kevin Gosse On BEST ANSWER

A certificate contains binary content, you shouldn't use a StreamReader to read it (it's meant to be used only for text).

Instead, read directly the content from the stream:

var resourceStream = Application.GetResourceStream(new Uri("myCert.der", UriKind.Relative));

var content = new byte[resourceStream.Stream.Length];
resourceStream.Stream.Read(content, 0, content.Length);

X509Certificate cert = new X509Certificate(content);