Error to Create a X509 Certificate to Xamarin.Forms project

Alexandre Lima 1 Reputation point
2020-12-18T13:11:03.997+00:00

I have this code:

var file2 = await FileSystem.OpenAppPackageFileAsync("certificado.p12");

                using (StreamReader sr = new StreamReader(file2))
                {
                    var bytes = sr.CurrentEncoding.GetBytes(sr.ReadToEnd());
                    var x509 = new X509Certificate2(bytes);
                }

It's return this exception:

System.Security.Cryptography.CryptographicException: Unable to decode certificate. ---> System.Security.Cryptography.CryptographicException: `MonoBtlsPkcs12.Import` failed.
  at Mono.Btls.MonoBtlsObject.CheckError (System.Boolean ok, System.String callerName) [0x00006] in /Users/builder/jenkins/workspace/archive-mono/2020-02/android/release/mcs/class/System/Mono.Btls/MonoBtlsObject.cs:95 
  at Mono.Btls.MonoBtlsObject.CheckError (System.Int32 ret, System.String callerName) [0x00000] in /Users/builder/jenkins/workspace/archive-mono/2020-02/android/release/mcs/class/System/Mono.Btls/MonoBtlsObject.cs:103 
  at Mono.Btls.MonoBtlsPkcs12.Import (System.Byte[] buffer, Microsoft.Win32.SafeHandles.SafePasswordHandle password) [0x0002e] in /Users/builder/jenkins/workspace/archive-mono/2020-02/android/release/mcs/class/System/Mono.Btls/MonoBtlsPkcs12.cs:117 

I tried it:

using (StreamReader sr = new StreamReader(file, Encoding.ASCII, true))
                {
                    byte[] raw = Encoding.ASCII.GetBytes(sr.ReadToEnd());
                    var x509 = new X509Certificate2(raw, string.Empty, X509KeyStorageFlags.DefaultKeySet);
                }

but return the same

Xamarin
Xamarin
A Microsoft open-source app platform for building Android and iOS apps with .NET and C#.
5,364 questions
{count} votes

Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.