private void Read_User_PKI()
 {
     try
     {
         BIO bio  = BIO.MemoryBuffer();
         var keys = File.ReadAllLines(KMS_Client_UC.Private_key_file);
         if (keys.Length > 25)
         {
             byte[] bytes;
             for (int i = 0; i < 28; i++)
             {
                 if (i == 0)
                 {
                     User = keys[i];
                 }
                 else
                 {
                     string temp = keys[i] + "\n";
                     bytes = Encoding.ASCII.GetBytes(temp);
                     bio.Write(bytes, bytes.Length);
                 }
             }
             user_priv_key = RSA.FromPrivateKey(bio);
         }
     }
     catch (Exception ex)
     { }
 }
Esempio n. 2
0
        public SslStreamServer(
            Stream stream,
            bool ownStream,
            string pskCiphers,
            byte[] pskPsk)
            : base(stream, ownStream)
        {
            this.pskCiphers = pskCiphers;
            this.pskPsk     = pskPsk;

            this.internalPskServerCallback = new PskServerCallbackHandler(InternalPskServerCallback);

            // Initialize the SslContext object
            InitializeServerContextUsingPsk(this.pskCiphers);

            // Initalize the Ssl object
            ssl = new Ssl(sslContext);
            // Initialze the read/write bio
            read_bio  = BIO.MemoryBuffer(false);
            write_bio = BIO.MemoryBuffer(false);
            // Set the read/write bio's into the the Ssl object
            ssl.SetBIO(read_bio, write_bio);
            read_bio.SetClose(BIO.CloseOption.Close);
            write_bio.SetClose(BIO.CloseOption.Close);
            // Set the Ssl object into server mode
            ssl.SetAcceptState();
        }
Esempio n. 3
0
        /// <summary>Create a DtlsFilter.</summary>
        /// <param name="key">A CryptoKey initialized by the OpenSSL.NET library.</param>
        /// <param name="cert">The path to the certificate to use.</param>
        /// <param name="ca_cert">The path to the ca certificate to use.</param>
        /// <param name="client">Use client initialization parameters.</param>
        public DtlsAssociation(ISender sender, CertificateHandler ch, PType ptype,
                               Ssl ssl, bool client) : base(sender, ch)
        {
            _ip     = new IdentifierPair();
            PType   = ptype;
            _ssl    = ssl;
            _client = client;
            _ssl.SetReadAhead(1);
            // Buggy SSL versions have issue with compression and dtls
            _ssl.SetOptions((int)SslOptions.SSL_OP_NO_COMPRESSION);
            if (client)
            {
                _ssl.SetConnectState();
            }
            else
            {
                _ssl.SetAcceptState();
            }

            // The ssl object will take control
            _read              = BIO.MemoryBuffer(false);
            _read.NonBlocking  = true;
            _write             = BIO.MemoryBuffer(false);
            _write.NonBlocking = true;

            _ssl.SetBIO(_read, _write);
            _ssl.DoHandshake();

            _buffer      = new byte[Int16.MaxValue];
            _buffer_sync = new object();
            _fe_lock     = 0;
        }
Esempio n. 4
0
        public SslStreamServer(
            Stream stream,
            bool ownStream,
            X509Certificate serverCertificate,
            bool clientCertificateRequired,
            X509Chain caCerts,
            SslProtocols enabledSslProtocols,
            SslStrength sslStrength,
            bool checkCertificateRevocation,
            RemoteCertificateValidationHandler remote_callback)
            : base(stream, ownStream)
        {
            checkCertificateRevocationStatus   = checkCertificateRevocation;
            remoteCertificateSelectionCallback = remote_callback;

            // Initialize the SslContext object
            InitializeServerContext(serverCertificate, clientCertificateRequired, caCerts, enabledSslProtocols, sslStrength, checkCertificateRevocation);

            // Initalize the Ssl object
            ssl = new Ssl(sslContext);

            sniCb = sniExt.ServerSniCb;
            sniExt.AttachSniExtensionServer(ssl.Handle, sslContext.Handle, sniCb);

            // Initialze the read/write bio
            read_bio  = BIO.MemoryBuffer(false);
            write_bio = BIO.MemoryBuffer(false);
            // Set the read/write bio's into the the Ssl object
            ssl.SetBIO(read_bio, write_bio);
            read_bio.SetClose(BIO.CloseOption.Close);
            write_bio.SetClose(BIO.CloseOption.Close);
            // Set the Ssl object into server mode
            ssl.SetAcceptState();
        }
Esempio n. 5
0
        public override PrivateKey ImportPrivateKey <PK>(EncodingFormat fmt, Stream source)
        {
            if (typeof(PK) == typeof(RsaPrivateKey))
            {
                using (BIO keyBio = BIO.MemoryBuffer())
                {
                    using (var ms = new MemoryStream())
                    {
                        source.CopyTo(ms);
                        keyBio.Write(ms.ToArray());
                    }

                    using (var key = CryptoKey.FromPrivateKey(keyBio, null))
                    {
                        var rsa = key.GetRSA();
                        return(new RsaPrivateKey(rsa.Size,
                                                 rsa.PrivateExponent.ToHexString(),
                                                 rsa.PrivateKeyAsPEM));
                    }
                }
            }
            else
            {
                throw new NotSupportedException("unsupported private key type");
            }
        }
Esempio n. 6
0
        protected void InitializeClientContextUsingPsk(string pskCiphers)
        {
            // Initialize the context with the specified ssl version
            //sslContext = new SslContext(SslMethod.SSLv23_client_method);
            sslContext = new SslContext(SslMethod.TLSv1_client_method);
            //sslContext = new SslContext(SslMethod.SSLv3_client_method);

            // Remove support for protocols that should not be supported
            sslContext.Options |= SslOptions.SSL_OP_NO_SSLv2;
            sslContext.Options |= SslOptions.SSL_OP_NO_SSLv3;

            // Set the enabled cipher list
            // WARNING: Using PSK ciphers requires that the PSK callback be set and initialize the identity and psk value.
            // Failure to do this will cause the PSK ciphers to be skipped when picking a shared cipher.
            // The result will be an error because of "no shared ciphers".
//            sslContext.SetCipherList("PSK-AES256-CBC-SHA:PSK-3DES-EDE-CBC-SHA:PSK-AES128-CBC-SHA:PSK-RC4-SHA");
            sslContext.SetCipherList(pskCiphers);

            // Set the PSK callbacks
            sslContext.SetPskClientCallback(this.internalPskClientCallback);

            // Set up the read/write bio's
            read_bio  = BIO.MemoryBuffer(false);
            write_bio = BIO.MemoryBuffer(false);
            ssl       = new Ssl(sslContext);
            ssl.SetBIO(read_bio, write_bio);
            read_bio.SetClose(BIO.CloseOption.Close);
            write_bio.SetClose(BIO.CloseOption.Close);
            ssl.SetConnectState();
        }
Esempio n. 7
0
        public void LoadCA(String PKCS12Filename)
        {
            FileInfo caPkcs12 = new FileInfo(PKCS12Filename);

            if (caPkcs12.Exists)
            {
                try
                {
                    Byte[] bPKCS12 = File.ReadAllBytes(caPkcs12.FullName);

                    // You need to write the CSR string to a BIO object as shown below.
                    BIO pkcs12BIO = BIO.MemoryBuffer();
                    pkcs12BIO.Write(bPKCS12);

                    X509Certificate cert = X509Certificate.FromPKCS12(pkcs12BIO, this.caPassword);

                    if (RootCA != null)
                    {
                        RootCA.Dispose();
                    }

                    RootCA = new X509CertificateAuthority(cert, cert.PrivateKey, new SimpleSerialNumber(1), cfg);
                }
                catch (Exception ex)
                {
                    RootCA = null;
                }
            }
        }
        public void TestGenRSA()
        {
            BigNumber e = null;

            //if (options.IsSet("3"))
            //    e = 3;
            //else if (options.IsSet("f4"))
            //    e = 0x10001;
            e = 0x10001;

            var rsagen = new RSA();

            rsagen.GenerateKeys(2048, e, GeneratorHandler, null);

            Cipher enc = null;
            //if (options.IsSet("des"))
            //    enc = Cipher.DES_CBC;
            //else if (options.IsSet("des3"))
            //    enc = Cipher.DES_EDE3_CBC;
            //else if (options.IsSet("idea"))
            //    enc = Cipher.Idea_CBC;
            //else if (options.IsSet("aes128"))
            //    enc = Cipher.AES_128_CBC;
            //else if (options.IsSet("aes192"))
            //    enc = Cipher.AES_192_CBC;
            //else if (options.IsSet("aes256"))
            //    enc = Cipher.AES_256_CBC;

            string passwd = null;

            using (var bio = BIO.MemoryBuffer())
            {
                rsagen.WritePrivateKey(bio, enc, OnPassword, passwd);

                var outfile = "openssl-rsagen-privatekey.txt";
                if (string.IsNullOrEmpty(outfile))
                {
                    Console.WriteLine(bio.ReadString());
                }
                else
                {
                    File.WriteAllText(outfile, bio.ReadString());
                }
            }

            using (var bio = BIO.MemoryBuffer())
            {
                rsagen.WritePublicKey(bio);

                var outfile = "openssl-rsagen-publickey.txt";
                if (string.IsNullOrEmpty(outfile))
                {
                    Console.WriteLine(bio.ReadString());
                }
                else
                {
                    File.WriteAllText(outfile, bio.ReadString());
                }
            }
        }
Esempio n. 9
0
        public static BIO GetInFile(string infile)
        {
            BIO bio;

            if (string.IsNullOrEmpty(infile))
            {
                bio = BIO.MemoryBuffer();
                var cin = Console.OpenStandardInput();
                var buf = new byte[1024];
                while (true)
                {
                    var len = cin.Read(buf, 0, buf.Length);

                    if (len == 0)
                    {
                        break;
                    }

                    bio.Write(buf, len);
                }

                return(bio);
            }

            return(BIO.File(infile, "r"));
        }
Esempio n. 10
0
        public static X509Certificate GetX509CertFromPKCS12(Byte[] PKCS12Data, String password)
        {
            BIO pkcs12BIO = BIO.MemoryBuffer();

            pkcs12BIO.Write(PKCS12Data);

            X509Certificate cert1 = X509Certificate.FromPKCS12(pkcs12BIO, password);

            using (MemoryStream ms = new MemoryStream())
            {
                using (BinaryWriter bw = new BinaryWriter(ms))
                    using (BIO bio = BIO.MemoryBuffer())
                    {
                        cert1.Write(bio);
                        Byte[] certData = bio.ReadBytes((Int32)bio.NumberWritten).Array;
                        bw.Write(certData);
                        bw.Close();
                    }


                BIO certBio = BIO.MemoryBuffer();
                certBio.Write(ms.ToArray());

                return(new X509Certificate(certBio));
            }
        }
Esempio n. 11
0
        public static X509Certificate CloneCertificate(X509Certificate cert)
        {
            BIO bio = BIO.MemoryBuffer();

            cert.Write(bio);

            return(new X509Certificate(bio));
        }
Esempio n. 12
0
        public void Bug3017248()
        {
            CryptoKey key    = new CryptoKey(new DSA(true));
            BIO       output = BIO.MemoryBuffer();

            key.WritePrivateKey(output, Cipher.Null, "password");
            output.SetClose(BIO.CloseOption.Close);
            Console.WriteLine(output.ReadString());
        }
Esempio n. 13
0
        public void Bug2993305()
        {
            BIO mb = BIO.MemoryBuffer();

            mb.Write("Some junk");
            ArraySegment <byte> result = mb.ReadBytes(0);

            Assert.AreEqual(0, result.Count);
        }
Esempio n. 14
0
        public static ox509.X509Certificate MonoX509ToOpenSsl(mx509.X509Certificate cert)
        {
            BIO bio = BIO.MemoryBuffer(true);

            bio.Write(cert.RawData);
            var ocert = ox509.X509Certificate.FromDER(bio);

            bio.Dispose();
            return(ocert);
        }
Esempio n. 15
0
        public static X509Certificate LoadCert(Byte[] X509Data)
        {
            BIO x509BIO = BIO.MemoryBuffer();

            x509BIO.Write(X509Data);

            X509Certificate cert = new X509Certificate(x509BIO);

            return(cert);
        }
Esempio n. 16
0
        public static X509Certificate LoadCert(Byte[] PKCS12Data, String password)
        {
            BIO pkcs12BIO = BIO.MemoryBuffer();

            pkcs12BIO.Write(PKCS12Data);

            X509Certificate cert = X509Certificate.FromPKCS12(pkcs12BIO, password);

            return(cert);
        }
Esempio n. 17
0
        public static mx509.X509Certificate OpenSslX509ToMonoX509(ox509.X509Certificate cert)
        {
            BIO bio = BIO.MemoryBuffer(true);

            cert.Write(bio);
            byte[] raw = new byte[bio.BytesPending];
            bio.Read(raw, raw.Length);
            bio.Dispose();
            return(new mx509.X509Certificate(raw));
        }
Esempio n. 18
0
 public void ExportAsDer(Stream s)
 {
     using (var xr = new X509Request(Pem))
     {
         using (var bio = BIO.MemoryBuffer())
         {
             xr.Write_DER(bio);
             var arr = bio.ReadBytes((int)bio.BytesPending);
             s.Write(arr.Array, arr.Offset, arr.Count);
         }
     }
 }
Esempio n. 19
0
        public static Byte[] X509ToByte(X509Certificate cert)
        {
            Byte[] ret = null;

            using (BIO bio2 = BIO.MemoryBuffer())
            {
                cert.Write(bio2);
                ret = bio2.ReadBytes((Int32)bio2.NumberWritten).Array;
            }

            return(ret);
        }
Esempio n. 20
0
        protected void InitializeClientContext(X509List certificates, SslProtocols enabledSslProtocols, SslStrength sslStrength, bool checkCertificateRevocation)
        {
            // Initialize the context with the specified SSL version
            // Initialize the context
            sslContext = new SslContext(SslMethod.SSLv23_client_method);

            // Remove support for protocols not specified in the enabledSslProtocols
            if ((enabledSslProtocols & SslProtocols.Ssl2) != SslProtocols.Ssl2)
            {
                sslContext.Options |= SslOptions.SSL_OP_NO_SSLv2;
            }
            if ((enabledSslProtocols & SslProtocols.Ssl3) != SslProtocols.Ssl3 &&
                ((enabledSslProtocols & SslProtocols.Default) != SslProtocols.Default))
            {
                // no SSLv3 support
                sslContext.Options |= SslOptions.SSL_OP_NO_SSLv3;
            }
            if ((enabledSslProtocols & SslProtocols.Tls) != SslProtocols.Tls &&
                (enabledSslProtocols & SslProtocols.Default) != SslProtocols.Default)
            {
                sslContext.Options |= SslOptions.SSL_OP_NO_TLSv1;
            }

            // Set the Local certificate selection callback
            sslContext.SetClientCertCallback(internalCertificateSelectionCallback);

            // Set the enabled cipher list
            sslContext.SetCipherList(GetCipherString(false, enabledSslProtocols, sslStrength));

            // Set the callbacks for remote cert verification and local cert selection
            if (remoteCertificateSelectionCallback != null)
            {
                sslContext.SetVerify(VerifyMode.SSL_VERIFY_PEER | VerifyMode.SSL_VERIFY_FAIL_IF_NO_PEER_CERT, remoteCertificateSelectionCallback);
            }

            // Set the CA list into the store
            if (caCertificates != null)
            {
                var store = new X509Store(caCertificates);
                sslContext.SetCertificateStore(store);
            }

            // Set up the read/write bio's
            read_bio  = BIO.MemoryBuffer(false);
            write_bio = BIO.MemoryBuffer(false);
            ssl       = new Ssl(sslContext);
            ssl.SetBIO(read_bio, write_bio);
            read_bio.SetClose(BIO.CloseOption.Close);
            write_bio.SetClose(BIO.CloseOption.Close);

            // Set the Ssl object into Client mode
            ssl.SetConnectState();
        }
Esempio n. 21
0
        public override void ExportArchive(PrivateKey pk, IEnumerable <Crt> certs, ArchiveFormat fmt, Stream target, string password = "")
        {
            var rsaPk = pk as RsaPrivateKey;

            if (rsaPk == null)
            {
                throw new NotSupportedException("unsupported private key type");
            }

            if (fmt == ArchiveFormat.PKCS12)
            {
                var x509Arr = certs.Select(x =>
                {
                    using (var bio = BIO.MemoryBuffer())
                    {
                        bio.Write(x.Pem);
                        return(new X509Certificate(bio));
                    }
                }).ToArray();

                using (var key = CryptoKey.FromPrivateKey(rsaPk.Pem, null))
                {
                    var caStack = new OpenSSL.Core.Stack <X509Certificate>();
                    for (int i = 1; i < x509Arr.Length; ++i)
                    {
                        caStack.Add(x509Arr[i]);
                    }

                    using (var pfx = new PKCS12(password == string.Empty ? null : password, key, x509Arr[0], caStack))
                    {
                        using (var bio = BIO.MemoryBuffer())
                        {
                            pfx.Write(bio);
                            var count = (int)bio.BytesPending;
                            var array = bio.ReadBytes(count);
                            target.Write(array.Array, 0, count);
                        }
                    }
                }

                foreach (var x in x509Arr)
                {
                    x.Dispose();
                }
            }
            else
            {
                throw new NotSupportedException("unsupported archive format");
            }
        }
Esempio n. 22
0
 public static void ConvertPemToDer(Stream source, Stream target)
 {
     using (var ts = new StreamReader(source))
     {
         using (var xr = new X509Request(ts.ReadToEnd()))
         {
             using (var bio = BIO.MemoryBuffer())
             {
                 xr.Write_DER(bio);
                 var arr = bio.ReadBytes((int)bio.BytesPending);
                 target.Write(arr.Array, arr.Offset, arr.Count);
             }
         }
     }
 }
Esempio n. 23
0
 public static void ConvertDerToPem(Stream source, Stream target)
 {
     using (var ms = new MemoryStream())
     {
         source.CopyTo(ms);
         using (var bio = BIO.MemoryBuffer())
         {
             bio.Write(ms.ToArray());
             using (var crt = X509Certificate.FromDER(bio))
             {
                 var pemBytes = Encoding.UTF8.GetBytes(crt.PEM);
                 target.Write(pemBytes, 0, pemBytes.Length);
             }
         }
     }
 }
Esempio n. 24
0
        public FileInfo SignCertFromRequest(Byte[] requestData, Boolean ca)
        {
            FileInfo file = null;

            using (BIO bio = new BIO(requestData))
                using (X509Request request = new X509Request(bio))
                {
                    file = new FileInfo(Path.Combine(certDir.FullName, request.Subject.Common + ".cer"));

                    using (X509Certificate certificate = RootCA.ProcessRequest(request, DateTime.Now.AddHours(-24), DateTime.Now + TimeSpan.FromDays(365), MessageDigest.SHA1))
                    {
                        if (ca)
                        {
                            certificate.AddExtension(new X509Extension(RootCA.Certificate, certificate, "basicConstraints", true, "CA:true"));
                            certificate.AddExtension(new X509Extension(RootCA.Certificate, certificate, "keyUsage", true, "critical, cRLSign, keyCertSign, digitalSignature"));
                            certificate.AddExtension(new X509Extension(RootCA.Certificate, certificate, "certificatePolicies", true, "2.5.29.32.0"));
                        }
                        else
                        {
                            certificate.AddExtension(new X509Extension(RootCA.Certificate, certificate, "basicConstraints", true, "CA:false"));
                        }

                        certificate.AddExtension(new X509Extension(RootCA.Certificate, certificate, "issuerAltName", true, "issuer:copy"));
                        certificate.AddExtension(new X509Extension(RootCA.Certificate, certificate, "nsComment", true, "IAM Tester Generated Certificate"));
                        certificate.AddExtension(new X509Extension(RootCA.Certificate, certificate, "subjectKeyIdentifier", true, "hash"));
                        certificate.AddExtension(new X509Extension(RootCA.Certificate, certificate, "authorityKeyIdentifier", true, "keyid,issuer:always"));
                        certificate.AddExtension(new X509Extension(RootCA.Certificate, certificate, "subjectAltName", true, "DNS:" + request.Subject.Common));

                        certificate.Sign(RootCA.Key, MessageDigest.SHA1);

                        using (FileStream fs = new FileStream(file.FullName, FileMode.Create, FileAccess.ReadWrite))
                            using (BinaryWriter bw = new BinaryWriter(fs))
                                using (BIO bio2 = BIO.MemoryBuffer())
                                {
                                    certificate.Write(bio2);
                                    Byte[] certData = bio2.ReadBytes((Int32)bio2.NumberWritten).Array;
                                    bw.Write(certData);
                                    bw.Close();
                                }

                        //Para atualizar com o tamanho e outros dados do arquivo
                        file = new FileInfo(file.FullName);
                    }
                }

            return(file);
        }
Esempio n. 25
0
        public static RsaKeyPair GenerateRsaPrivateKey(int bits = 2048, BigNumber e = null,
                                                       RsaKeyGeneratorCallback cb = null, object cbArg = null)
        {
            if (e == null)
            {
                e = E_F4;
            }

            using (var rsa = new RSA())
            {
                BigNumber.GeneratorHandler cbWrapper = null;
                if (cb != null)
                {
                    cbWrapper = (x, y, z) => cb(x, y, z);
                }

                Cipher          enc   = null;
                string          pwd   = null;
                PasswordHandler pwdCb = null;
                // If we choose to encrypt:
                //      Cipher.DES_CBC;
                //      Cipher.DES_EDE3_CBC;
                //      Cipher.Idea_CBC;
                //      Cipher.AES_128_CBC;
                //      Cipher.AES_192_CBC;
                //      Cipher.AES_256_CBC;
                //   and pwd != null || pwdCb != null
                // We can use a pwdCb to get a password interactively or we can
                // simply pass in a fixed password string (no cbPwd, just pwd)
                if (pwd != null)
                {
                    pwdCb = DefaultPasswordHandler;
                }

                // Ref:  http://openssl.org/docs/manmaster/crypto/RSA_generate_key_ex.html
                rsa.GenerateKeys(bits, e, cbWrapper, cbArg);

                using (var bio = BIO.MemoryBuffer())
                {
                    // Ref:  http://openssl.org/docs/manmaster/crypto/PEM_write_bio_RSAPrivateKey.html
                    rsa.WritePrivateKey(bio, enc, pwdCb, pwd);
                    return(new RsaKeyPair(bits, e.ToHexString(), bio.ReadString()));
                }
            }
        }
Esempio n. 26
0
            /// <summary>
            /// Converts a certificate and private key to a PKCS#12 (.PFX) file.
            /// </summary>
            public static void ConvertToPfx(Stream keyPemSource, Stream crtPemSource, Stream isrPemSource, Stream pfxTarget)
            {
                using (BIO keyBio = BIO.MemoryBuffer(),
                       crtBio = BIO.MemoryBuffer(),
                       isrBio = BIO.MemoryBuffer())
                {
                    using (var ms = new MemoryStream())
                    {
                        keyPemSource.CopyTo(ms);
                        keyBio.Write(ms.ToArray());
                    }
                    using (var ms = new MemoryStream())
                    {
                        crtPemSource.CopyTo(ms);
                        crtBio.Write(ms.ToArray());
                    }
                    using (var ms = new MemoryStream())
                    {
                        isrPemSource.CopyTo(ms);
                        isrBio.Write(ms.ToArray());
                    }

                    using (var key = CryptoKey.FromPrivateKey(keyBio, null))
                    {
                        using (var crt = new X509Certificate(crtBio))
                        {
                            using (var isr = new X509Certificate(isrBio))
                            {
                                var isrStack = new OpenSSL.Core.Stack <X509Certificate>();
                                isrStack.Add(isr);

                                using (var pfx = new PKCS12(null, key, crt, isrStack))
                                {
                                    using (var pfxBio = BIO.MemoryBuffer())
                                    {
                                        pfx.Write(pfxBio);
                                        var arr = pfxBio.ReadBytes((int)pfxBio.BytesPending);
                                        pfxTarget.Write(arr.Array, arr.Offset, arr.Count);
                                    }
                                }
                            }
                        }
                    }
                }
            }
Esempio n. 27
0
        public void WriteChain(X509Certificate cert, X509Chain chain)
        {
            FileInfo p7b = new FileInfo(Path.Combine(certDir.FullName, cert.Subject.Common + ".chain"));

            using (FileStream fs = new FileStream(p7b.FullName, FileMode.Create, FileAccess.ReadWrite))
                using (BinaryWriter bw = new BinaryWriter(fs))
                {
                    BIO bio = BIO.MemoryBuffer();

                    foreach (X509Certificate c in chain)
                    {
                        c.Write(bio);
                    }

                    Byte[] certData = bio.ReadBytes((Int32)bio.NumberWritten).Array;
                    bw.Write(certData);
                    bw.Close();
                }
        }
Esempio n. 28
0
 /// <summary>
 /// Supports importing certificates from <see cref="EncodingFormat.PEM">PEM</see>
 /// and <see cref="EncodingFormat.DER">DER</see> formats.
 /// </summary>
 public override Crt ImportCertificate(EncodingFormat fmt, Stream source)
 {
     if (fmt == EncodingFormat.DER)
     {
         using (var ms = new MemoryStream())
         {
             source.CopyTo(ms);
             using (var bio = BIO.MemoryBuffer())
             {
                 bio.Write(ms.ToArray());
                 using (var x509 = X509Certificate.FromDER(bio))
                 {
                     return(new Crt
                     {
                         Pem = x509.PEM
                     });
                 }
             }
         }
     }
     else if (fmt == EncodingFormat.PEM)
     {
         using (var r = new StreamReader(source))
         {
             using (var bio = BIO.MemoryBuffer())
             {
                 bio.Write(r.ReadToEnd());
                 using (var x509 = new X509Certificate(bio))
                 {
                     return(new Crt
                     {
                         Pem = x509.PEM
                     });
                 }
             }
         }
     }
     else
     {
         throw new NotSupportedException("encoding format has not been implemented");
     }
 }
Esempio n. 29
0
        public static X509Certificate LoadCert(String X509Filename)
        {
            FileInfo certFile = new FileInfo(X509Filename);

            if (certFile.Exists)
            {
                Byte[] bX509 = File.ReadAllBytes(certFile.FullName);

                BIO x509BIO = BIO.MemoryBuffer();
                x509BIO.Write(bX509);

                X509Certificate cert = X509Certificate.FromDER(x509BIO);

                return(cert);
            }
            else
            {
                return(null);
            }
        }
Esempio n. 30
0
        private String BuildPKCS12AndSave(String filename, String password, CryptoKey key, X509Certificate cert)
        {
            String retCert = "";

            retCert = BuildPKCS12(password, key, cert);

            using (FileStream fs = new FileStream(filename, FileMode.Create, FileAccess.ReadWrite))
                using (BinaryWriter bw = new BinaryWriter(fs))
                    using (BIO bio = BIO.MemoryBuffer())
                    {
                        Byte[] certData = Convert.FromBase64String(retCert);
                        bw.Write(certData);
                        bw.Close();
                    }

            /*
             * using (PKCS12 pfx = new PKCS12(password, key, cert, new OpenSSL.Core.Stack<X509Certificate>()))
             * using (FileStream fs = new FileStream(filename, FileMode.Create, FileAccess.ReadWrite))
             * using (BinaryWriter bw = new BinaryWriter(fs))
             * using (BIO bio = BIO.MemoryBuffer())
             * {
             *  pfx.Write(bio);
             *  Byte[] certData = bio.ReadBytes((Int32)bio.NumberWritten).Array;
             *  bw.Write(certData);
             *  bw.Close();
             * }*/


            using (FileStream fs = new FileStream(filename.Replace(".pfx", ".cer"), FileMode.Create, FileAccess.ReadWrite))
                using (BinaryWriter bw = new BinaryWriter(fs))
                    using (BIO bio = BIO.MemoryBuffer())
                    {
                        cert.Write(bio);
                        Byte[] certData = bio.ReadBytes((Int32)bio.NumberWritten).Array;
                        bw.Write(certData);
                        bw.Close();
                    }

            return(retCert);
        }