Esempio n. 1
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. 2
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;
                }
            }
        }
 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. 4
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. 5
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. 6
0
        override protected bool HandleIncoming(MemBlock data, out MemBlock app_data)
        {
            app_data = null;
            int count = 0;

            lock (_buffer_sync) {
                if (data != null)
                {
                    data.CopyTo(_buffer, 0);
                    _read.Write(_buffer, data.Length);
                }

                count = _ssl.Read(_buffer, _buffer.Length);
                if (count > 0)
                {
                    app_data = MemBlock.Copy(_buffer, 0, count);
                }
            }

            if (app_data != null)
            {
                // If the read was successful, Dtls has received an incoming data
                // message and decrypted it
                return(true);
            }
            else
            {
                SslError error = _ssl.GetError(count);
                if (error == SslError.SSL_ERROR_WANT_READ)
                {
                    if (SslState == SslState.OK)
                    {
                        UpdateState(States.Active);
                        // In the SslCtx verify, there's no way to get the underlying Sender
                        _ch.Verify(RemoteCertificate, Sender);
                    }
                    HandleWouldBlock();
                }
                else if (error == SslError.SSL_ERROR_SSL)
                {
                    var ose = new OpenSslException();
                    Close("Received unrecoverable error: " + ose.ToString());
                    throw ose;
                }
                else if (error == SslError.SSL_ERROR_ZERO_RETURN)
                {
                    Close("Received clean close notification");
                }
                else
                {
                    ProtocolLog.WriteIf(ProtocolLog.SecurityExceptions,
                                        "Receive other: " + error);
                }
            }
            return(false);
        }
Esempio n. 7
0
        public static X509Certificate LoadCert(Byte[] X509Data)
        {
            BIO x509BIO = BIO.MemoryBuffer();

            x509BIO.Write(X509Data);

            X509Certificate cert = new X509Certificate(x509BIO);

            return(cert);
        }
Esempio n. 8
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. 9
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. 10
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. 11
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. 12
0
        private void Check_PKI()
        {
            BIO bio  = BIO.MemoryBuffer();
            var keys = File.ReadAllLines(Private_Keys);

            byte[] bytes;
            for (int i = 1; i < 28; i++)
            {
                string temp = keys[i] + "\n";

                bytes = Encoding.ASCII.GetBytes(temp);

                bio.Write(bytes, bytes.Length);
            }

            var rsa = RSA.FromPrivateKey(bio);

            bytes = Encoding.ASCII.GetBytes("Hello");

            byte[] ctext = rsa.PublicEncrypt(bytes, RSA.Padding.PKCS1);

            byte[] ptext = rsa.PrivateDecrypt(ctext, RSA.Padding.PKCS1);
        }
Esempio n. 13
0
        private void Read_Users_PKI()
        {
            if (Users_PKI == null)
            {
                Users_PKI = new Dictionary <string, RSA>();
            }
            else
            {
                Users_PKI.Clear();
            }

            var keys = File.ReadAllLines(KMS_Client_UC.Public_key_file);

            if (keys.Length >= 99)
            {
                byte[] bytes;
                for (int i = 0; i < 10; i++)
                {
                    BIO    bio = BIO.MemoryBuffer();
                    string user = "", temp;
                    for (int j = i * 10; j < (i + 1) * 10; j++)
                    {
                        if (j == i * 10)
                        {
                            user = keys[j];
                        }
                        else
                        {
                            temp  = keys[j] + "\n";
                            bytes = Encoding.ASCII.GetBytes(temp);
                            bio.Write(bytes, bytes.Length);
                        }
                    }
                    Users_PKI.Add(user, RSA.FromPublicKey(bio));
                }
            }
        }
Esempio n. 14
0
 /// <summary>
 /// Support exporting certificates to <see cref="EncodingFormat.PEM">PEM</see>
 /// and <see cref="EncodingFormat.DER">DER</see> formats.
 /// </summary>
 public override void ExportCertificate(Crt cert, EncodingFormat fmt, Stream target)
 {
     if (fmt == EncodingFormat.PEM)
     {
         var bytes = Encoding.UTF8.GetBytes(cert.Pem);
         target.Write(bytes, 0, bytes.Length);
     }
     else if (fmt == EncodingFormat.DER)
     {
         using (BIO bioPem = BIO.MemoryBuffer())
         {
             bioPem.Write(cert.Pem);
             using (var x509 = new X509Certificate(bioPem))
             {
                 var bytes = x509.DER;
                 target.Write(bytes, 0, bytes.Length);
             }
         }
     }
     else
     {
         throw new NotSupportedException("unsupported encoding format");
     }
 }
Esempio n. 15
0
 /// <summary>
 /// Returns the cipher's LongName
 /// </summary>
 /// <param name="bio"></param>
 public override void Print(BIO bio)
 {
     bio.Write("CipherContext: " + cipher.LongName);
 }
Esempio n. 16
0
 /// <summary>
 /// Prints the LongName of this cipher.
 /// </summary>
 /// <param name="bio"></param>
 public override void Print(BIO bio)
 {
     bio.Write(LongName);
 }
Esempio n. 17
0
        public void LoadOrCreateCA(String PKCS12Filename, X509Name Name, subjectAltName altNames)
        {
            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
                {
                    RootCA = null;
                }
            }

            if (RootCA == null)
            {
                X509V3ExtensionList ext = new X509V3ExtensionList();

                ext.Add(new X509V3ExtensionValue("nsComment", true, "SafeID - IAM Generated Certificate"));
                ext.Add(new X509V3ExtensionValue("basicConstraints", true, "CA:true"));
                //ext.Add(new X509V3ExtensionValue("keyUsage", true, "critical, cRLSign, keyCertSign, digitalSignature"));
                ext.Add(new X509V3ExtensionValue("subjectKeyIdentifier", true, "hash"));
                ext.Add(new X509V3ExtensionValue("authorityKeyIdentifier", true, "keyid,issuer:always"));

                if (altNames != null)
                {
                    foreach (Uri u in altNames.Uri)
                    {
                        ext.Add(new X509V3ExtensionValue("subjectAltName", true, "URI:" + u.AbsoluteUri.ToLower()));
                    }

                    foreach (String m in altNames.Mail)
                    {
                        ext.Add(new X509V3ExtensionValue("subjectAltName", true, "email:" + m));
                    }

                    foreach (String s in altNames.Dns)
                    {
                        ext.Add(new X509V3ExtensionValue("subjectAltName", true, "DNS:" + s));
                    }

                    foreach (String s in altNames.Text)
                    {
                        ext.Add(new X509V3ExtensionValue("subjectAltName", true, "otherName:1.2.3.4;UTF8:" + s));
                    }
                }

                RootCA = X509CertificateAuthority.SelfSigned(new SimpleSerialNumber(), CreateNewRSAKey(2048), MessageDigest.SHA1, Name, DateTime.Now.AddHours(-24), (DateTime.Now.AddYears(10) - DateTime.Now), ext);

                BuildPKCS12AndSave(caPkcs12.FullName, this.caPassword, RootCA.Key, RootCA.Certificate);
            }
        }
Esempio n. 18
0
 /// <summary>
 /// Prints the long name
 /// </summary>
 /// <param name="bio"></param>
 public override void Print(BIO bio)
 {
     bio.Write("MessageDigestContext: " + this.md.LongName);
 }
Esempio n. 19
0
        private void InternalReadCallback(IAsyncResult asyncResult)
        {
            InternalAsyncResult internalAsyncResult = (InternalAsyncResult)asyncResult.AsyncState;
            bool haveDataToReturn = false;

            try
            {
                int bytesRead = 0;
                try
                {
                    bytesRead = innerStream.EndRead(asyncResult);
                }
                catch (Exception ex)
                {
                    // Set the exception into the internal async result
                    internalAsyncResult.SetComplete(ex);
                }
                if (bytesRead <= 0)
                {
                    // Zero byte read most likely indicates connection closed (if it's a network stream)
                    internalAsyncResult.SetComplete(0);
                    return;
                }
                else
                {
                    // Copy encrypted data into the SSL read_bio
                    read_bio.Write(read_buffer, bytesRead);
                    if (handShakeState == HandshakeState.InProcess ||
                        handShakeState == HandshakeState.RenegotiateInProcess)
                    {
                        // We are in the handshake, complete the async operation to fire the async
                        // handshake callback for processing
                        internalAsyncResult.SetComplete(bytesRead);
                        return;
                    }
                    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)
                            {
                                // if we have bytes pending in the write bio.
                                // the client has requested a renegotiation
                                if (write_bio.BytesPending > 0)
                                {
                                    // Start the renegotiation by writing the write_bio data, and use the RenegotiationWriteCallback
                                    // to handle the rest of the renegotiation
                                    ArraySegment <byte> buf = write_bio.ReadBytes((int)write_bio.BytesPending);
                                    innerStream.BeginWrite(buf.Array, 0, buf.Count, new AsyncCallback(RenegotiationWriteCallback), internalAsyncResult);
                                    return;
                                }
                                // no data in the out bio, we just need more data to complete the record
                                //break;
                            }
                            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
                            {
                                throw new OpenSslException();
                            }
                        }
                        if (decryptedBytesRead > 0)
                        {
                            // 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, decryptedBytesRead);
                            decrypted_data_stream.Seek(pos, SeekOrigin.Begin);
                            haveDataToReturn = true;
                        }

                        // See if we have more data to process
                        nBytesPending = read_bio.BytesPending;
                    }
                    // Check to see if we have data to return, if not, fire the async read again
                    if (!haveDataToReturn)
                    {
                        innerStream.BeginRead(read_buffer, 0, read_buffer.Length, new AsyncCallback(InternalReadCallback), internalAsyncResult);
                    }
                    else
                    {
                        int bytesReadIntoUserBuffer = 0;

                        // Read the data into the buffer provided by the user (now hosted in the InternalAsyncResult)
                        bytesReadIntoUserBuffer = decrypted_data_stream.Read(internalAsyncResult.Buffer, internalAsyncResult.Offset, internalAsyncResult.Count);

                        internalAsyncResult.SetComplete(bytesReadIntoUserBuffer);
                    }
                }
            }
            catch (Exception ex)
            {
                internalAsyncResult.SetComplete(ex);
            }
        }
Esempio n. 20
0
 /// <summary>
 /// Prints MessageDigest
 /// </summary>
 /// <param name="bio"></param>
 public override void Print(BIO bio)
 {
     bio.Write("MessageDigest");
 }