Exemple #1
0
        /*
         * public override int Read(byte[] buffer, int offset, int count)
         * {
         *      // Check to see if we need to reset the decrypted data stream
         *      if (decrypted_data_stream.Position == decrypted_data_stream.Length)
         *      {
         *              // reset the stream
         *              decrypted_data_stream.Seek(0, SeekOrigin.Begin);
         *              decrypted_data_stream.SetLength(0);
         *      }
         *      // Check to see if we have data in the decrypted memory stream, if so return it
         *      if (decrypted_data_stream.Position > 0 && (decrypted_data_stream.Position != decrypted_data_stream.Length))
         *      {
         *              return decrypted_data_stream.Read(buffer, offset, count);
         *      }
         *
         *      // No pre-existing data in the stream, read from the innerStream
         *      int bytesRead = 0;
         *      bool haveDataToReturn = false;
         *
         *      while (! haveDataToReturn)
         *      {
         *              try
         *              {
         *                      bytesRead = innerStream.Read(read_buffer, 0, read_buffer.Length);
         *              }
         *              catch(System.IO.IOException ex)
         *              {
         *                      //!!TODO - log exception
         *                      return 0;
         *              }
         *              // if we have data, let's process it
         *              if (bytesRead > 0)
         *              {
         *                      // Copy encrypted data into the SSL read_bio
         *                      read_bio.Write(read_buffer, bytesRead);
         *                      if (inHandshakeLoop)
         *                      {
         *                              if (ProcessHandshake())
         *                              {
         *                                      inHandshakeLoop = false;
         *                              }
         *                      }
         *                      //!!else -- Process data in read_bio after handshake if there is any
         *                      {
         *                              uint nBytesPending = read_bio.BytesPending;
         *                              byte[] decrypted_buf = new byte[SSL3_RT_MAX_PACKET_SIZE];
         *                              while (nBytesPending > 0)
         *                              {
         *                                      int decryptedBytesRead = ssl.Read(decrypted_buf, decrypted_buf.Length);
         *                                      if (decryptedBytesRead <= 0)
         *                                      {
         *                                              SslError lastError = ssl.GetError(decryptedBytesRead);
         *                                              if (lastError == SslError.SSL_ERROR_WANT_READ)
         *                                              {
         *                                                      // Renogiated requested by the client
         *                                                      if (write_bio.BytesPending > 0)
         *                                                      {
         *                                                              inHandshakeLoop = true;
         *                                                              if (ProcessHandshake())
         *                                                              {
         *                                                                      inHandshakeLoop = false;
         *                                                              }
         *                                                      }
         *                                                      //!!break; -- continue processing the handshake data
         *                                              }
         *                                              else if (lastError == SslError.SSL_ERROR_WANT_WRITE)
         *                                              {
         *                                                      // unexpected error!
         *                                                      //!!TODO debug log
         *                                              }
         *                                              else if (lastError == SslError.SSL_ERROR_ZERO_RETURN)
         *                                              {
         *                                                      // Shutdown alert
         *                                                      SendShutdownAlert();
         *                                                      break;
         *                                              }
         *                                              else
         *                                              {
         *                                                      //!!TODO - log last error, throw expection
         *                                                      break;
         *                                              }
         *                                      }
         *                                      // Write decrypted data to memory stream
         *                                      long pos = decrypted_data_stream.Position;
         *                                      decrypted_data_stream.Seek(0, SeekOrigin.End);
         *                                      decrypted_data_stream.Write(decrypted_buf, 0, decrypted_buf.Length);
         *                                      decrypted_data_stream.Seek(pos, SeekOrigin.Begin);
         *                                      haveDataToReturn = true;
         *
         *                                      // See if we have more data to process
         *                                      nBytesPending = read_bio.BytesPending;
         *                              }
         *                      }
         *              }
         *      }
         *      // Read data from the decrypted data stream into the user buffer
         *      return decrypted_data_stream.Read(buffer, offset, count);
         * }
         */

        public void SendShutdownAlert()
        {
            int nShutdownRet = ssl.Shutdown();

            if (nShutdownRet == 0)
            {
                uint nBytesToWrite = write_bio.BytesPending;
                if (nBytesToWrite <= 0)
                {
                    // unexpected error
                    //!!TODO log error
                    return;
                }
                ArraySegment <byte> buf = write_bio.ReadBytes((int)nBytesToWrite);
                if (buf.Count <= 0)
                {
                    //!!TODO - log error
                }
                else
                {
                    // Write the shutdown alert to the stream
                    innerStream.Write(buf.Array, 0, buf.Count);
                }
            }
        }
Exemple #2
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));
            }
        }
Exemple #3
0
        /// <summary>
        /// Calls EVP_SignFinal()
        /// </summary>
        /// <param name="md"></param>
        /// <param name="bio"></param>
        /// <param name="pkey"></param>
        /// <returns></returns>
        public static byte[] Sign(MessageDigest md, BIO bio, CryptoKey pkey)
        {
            BIO bmd = BIO.MessageDigest(md);

            bmd.Push(bio);

            while (true)
            {
                ArraySegment <byte> bytes = bmd.ReadBytes(1024 * 4);
                if (bytes.Count == 0)
                {
                    break;
                }
            }

            MessageDigestContext ctx = new MessageDigestContext(bmd);

            byte[] sig = new byte[pkey.Size];
            uint   len = (uint)sig.Length;

            Native.ExpectSuccess(Native.EVP_SignFinal(ctx.Handle, sig, ref len, pkey.Handle));
            byte[] ret = new byte[len];
            Buffer.BlockCopy(sig, 0, ret, 0, (int)len);
            return(ret);
        }
        public void Bug2993305()
        {
            BIO mb = BIO.MemoryBuffer();

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

            Assert.AreEqual(0, result.Count);
        }
 public void Bug3524222()
 {
     byte[] pattern = { 1, 2, 3 };
     byte[] buf     = (byte[])pattern.Clone();
     using (BIO bio = new BIO(buf)) {
         buf[1] = 1;
         Assert.AreEqual(pattern, bio.ReadBytes(3).Array);
     }
 }
Exemple #6
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);
        }
        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);
        }
        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();
                }
        }
Exemple #9
0
        /// <summary>
        /// Calls EVP_VerifyFinal()
        /// </summary>
        /// <param name="md"></param>
        /// <param name="bio"></param>
        /// <param name="sig"></param>
        /// <param name="pkey"></param>
        /// <returns></returns>
        public static bool Verify(MessageDigest md, BIO bio, byte[] sig, CryptoKey pkey)
        {
            BIO bmd = BIO.MessageDigest(md);

            bmd.Push(bio);

            while (true)
            {
                ArraySegment <byte> bytes = bmd.ReadBytes(1024 * 4);
                if (bytes.Count == 0)
                {
                    break;
                }
            }

            MessageDigestContext ctx = new MessageDigestContext(bmd);

            int ret = Native.ExpectSuccess(Native.EVP_VerifyFinal(ctx.Handle, sig, (uint)sig.Length, pkey.Handle));

            return(ret == 1);
        }
Exemple #10
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);
        }
Exemple #11
0
        private String BuildPKCS12(String password, CryptoKey key, X509Certificate cert)
        {
            String retCert = "";

            //Copia para memória
            using (MemoryStream ms = new MemoryStream())
            {
                using (PKCS12 pfx = new PKCS12(password, key, cert, new OpenSSL.Core.Stack <X509Certificate>()))
                    using (BinaryWriter bw = new BinaryWriter(ms))
                        using (BIO bio = BIO.MemoryBuffer())
                        {
                            pfx.Write(bio);
                            Byte[] certData = bio.ReadBytes((Int32)bio.NumberWritten).Array;
                            bw.Write(certData);
                            bw.Close();
                        }

                retCert = Convert.ToBase64String(ms.ToArray());
            }

            return(retCert);
        }