ManagedOpenSsl in .net core throws "System.BadImageFormatException:"


I have been facing multiple challenges with getting the ManagedOpenSsl to work with .Net Core. I downloaded ManagedOpenSsl.NetCore from nuget package.

My End Goal is to create a .pfx file from certificate PEM and private key. In the below code, ocert.KeyPair.PrivateKey is the certificate private key and ocert.CertificatePem is the certificate PEM.

ManagedOpenSsl.NetCore.Core.BIO key_bio = new ManagedOpenSsl.NetCore.Core.BIO(ocert.KeyPair.PrivateKey);
            ManagedOpenSsl.NetCore.Core.BIO cert_bio = new ManagedOpenSsl.NetCore.Core.BIO(ocert.CertificatePem);

            ManagedOpenSsl.NetCore.Crypto.CryptoKey key = ManagedOpenSsl.NetCore.Crypto.CryptoKey.FromPrivateKey(ocert.KeyPair.PrivateKey, "xxxxx");
            ManagedOpenSsl.NetCore.X509.X509Certificate cert = new ManagedOpenSsl.NetCore.X509.X509Certificate(cert_bio);
            ManagedOpenSsl.NetCore.Core.Stack<ManagedOpenSsl.NetCore.X509.X509Certificate> hmm = new ManagedOpenSsl.NetCore.Core.Stack<ManagedOpenSsl.NetCore.X509.X509Certificate>();

            var pfx = new ManagedOpenSsl.NetCore.X509.PKCS12(password, key, cert, hmm); // <-- 
            ManagedOpenSsl.NetCore.X509.X509Certificate certpfx = pfx.Certificate;

I'm getting error

{System.TypeInitializationException: The type initializer for 'ManagedOpenSsl.NetCore.Core.Native' threw an exception. ---> System.BadImageFormatException: An attempt was made to load a program with an incorrect format. (Exception from HRESULT: 0x8007000B) at ManagedOpenSsl.NetCore.Core.Native.SSLeay() at ManagedOpenSsl.NetCore.Core.Version.get_Library() at ManagedOpenSsl.NetCore.Core.Native..cctor() --- End of inner exception stack trace - in the line of code `ManagedOpenSsl.NetCore.Core.BIO key_bio = new ManagedOpenSsl.NetCore.Core.BIO(ocert.KeyPair.PrivateKey);

In Visual Studio 2017 project properties , I have set the Platform Target to "Any CPU", still the issue occurs. Also any implementation on how to save the pfx.Certificate to a specific folder in .pfx format ? Any help will be appreciated. Been struggling with this issue for a while now.

asked on Stack Overflow Feb 18, 2018 by Siva Shan • edited Feb 18, 2018 by Siva Shan

1 Answer


Since this is unmanaged code, you need to be specific about the bitness. Do not target "Any CPU". Compile you project for the bitness of target program. If you will be using it on both x86 and x64 processes, compile into 2 different binaries.

answered on Stack Overflow Feb 22, 2018 by Madhavi Phadnis

User contributions licensed under CC BY-SA 3.0