Ejemplo n.º 1
0
        public static unsafe TimeSpan Multiply( int N )
        {
            if ( N > max )
            {
                N = max;
            }

            int i, j, k;
            var accessor = new Arrays();
            for ( i = 0; i < N; i++ )
            {
                for ( j = 0; j < N; j++ )
                {
                    accessor.C[i * N + j] = 0;
                    accessor.B[i * N + j] = i * j;
                    accessor.A[i * N + j] = i * j;
                }
            }

            Stopwatch stopwatch = Stopwatch.StartNew();

            for ( i = 0; i < N; i++ )
            {
                for ( k = 0; k < N; k++ )
                {
                    for ( j = 0; j < N; j++ )
                    {
                        accessor.C[i * N + j] += accessor.A[i * N + k] * accessor.B[k * N + j];
                    }
                }
            }

            stopwatch.Stop();
            return stopwatch.Elapsed;
        }
Ejemplo n.º 2
0
		static void Main(string[] args)
		{
			List list = new List();

			list.Add("A");
			list.Add("B");
			list.Add("C");
			list.Add("D");
			list.Add("E");
			list.Add("F");
			list.Add("G");
			list.Add("H");

			list.ListNodes();
			Console.WriteLine();

			Console.WriteLine();
			Console.WriteLine("Deleting node 8");
			list.Delete(8);
			list.ListNodes();

			Console.WriteLine();
			Console.WriteLine("Position 5: " + list.Retrieve(5).NodeContent);

			Console.WriteLine();
			Console.WriteLine("Deleting node 5");
			list.Delete(5);

			Console.WriteLine();
			Console.WriteLine("Position 5: " + list.Retrieve(5).NodeContent);

			Console.WriteLine();
			list.ListNodes();

			Console.ReadLine();

			//double linked list
			DoubleLinkedList listdl = new DoubleLinkedList();
			listdl.Insert("1");
			listdl.Insert("2");
			listdl.Insert("3");

			DoubleLink link4 = listdl.Insert("4");
			listdl.Insert("5");
			Console.WriteLine("List: " + listdl);

			listdl.InsertAfter(link4, "[4a]");
			Console.WriteLine("List: " + listdl);
			Console.Read();

			link4 = listdl.Find ("[4a]");
			listdl.Delete (link4);
			Console.WriteLine ("List after delete:" + listdl);

			listdl.Delete ();
			Console.WriteLine ("list after delete first:" + listdl);
			Console.Read ();

			string str = "hello reverse words hello";
			Console.WriteLine(str);
			StringExamples mystring = new StringExamples();
			Console.WriteLine(mystring.reverseWords(str));

			Console.WriteLine("Reverse Recursively");
			Console.WriteLine(mystring.reverseRecursively(str));
			string str2 = "Reverse words in-place";	
			Console.WriteLine(str2);
			Console.WriteLine(mystring.reverseWordsInPlace(str2));
			string str3 = "remove whitespace\t\t\tin place";
			Console.WriteLine(str3);
			Console.WriteLine(mystring.removeWhitespaceInplace(str3));
			string str4 = "AAA BBB CC D EE A";
			Console.WriteLine("remove duplicate characters" + str4);
			Console.Write(mystring.removeDuplicateChars(str4));

			char c=mystring.firstNonRepeatedCharacter(str);
			Console.WriteLine("\nThe first non repeated character in '" + str + "' is :  " + c);

			BinaryTree<int> btree = new BinaryTree<int>();
			//btree.Root = new BinaryTreeNode<int>(1);
			//btree.Root.Left = new BinaryTreeNode<int>(2);
			//btree.Root.Right = new BinaryTreeNode<int>(3);

			//btree.Root.Left.Left = new BinaryTreeNode<int>(4);
			//btree.Root.Right.Right = new BinaryTreeNode<int>(5);

			//btree.Root.Left.Left.Right = new BinaryTreeNode<int>(6);
			//btree.Root.Right.Right.Right = new BinaryTreeNode<int>(7);

			//btree.Root.Right.Right.Right.Right = new BinaryTreeNode<int>(8);
				Random rnd = new Random();
				int j;
				for (int i = 0; i < 8; i++) {
					j = rnd.Next (1, 20);
					Console.Write (j + ",");
					btree.Add (j);
				}
				Console.WriteLine ("");
					// manual sorting?  
				btree.PreorderTraversal (btree.Root);
				btree.Add (4);
				Console.WriteLine ("\n Added 4");
				btree.InorderTraversal (btree.Root);
				Console.WriteLine ("\n Remove 4");

				btree.Remove (4);
				btree.InorderTraversal (btree.Root);

				Arrays arr = new Arrays();
				//Console.WriteLine("\nfind dup int:" + arr.FindDuplicateInt ());

				Console.WriteLine ("\nfind missing int: " + arr.FindMissingInt ());
				int [] arr2 = {-1,6,-2,-3,5,-7,5,-10,0,1,9,1,-2};
				int start;
				int end;
				Console.WriteLine ("\nfind best subsequence total: " + arr.FindBestSubsequence(arr2,out start, out end) + "start:"+ start + "end:" + end);
				Console.WriteLine ("\nfind best contiguous total: " + arr.HighestContiguousSum(arr2,out start, out end) + "start:"+ start + "end:" + end);
				Console.WriteLine ("\n2 largest: " + arr.sumTwoLargest (arr2));

				Console.WriteLine("\nsum 3 largest: " + arr.sumNLargest(arr2,3));

		}
Ejemplo n.º 3
0
        /// <summary>
        /// Called when hash is too small (&gt; 50% occupied) or too large (&lt; 20%
        /// occupied).
        /// </summary>
        private void Rehash(int newSize, bool hashOnData)
        {
            int newMask = newSize - 1;

            bytesUsed.AddAndGet(RamUsageEstimator.NUM_BYTES_INT32 * (newSize));
            int[] newHash = new int[newSize];
            Arrays.Fill(newHash, -1);
            for (int i = 0; i < hashSize; i++)
            {
                int e0 = ids[i];
                if (e0 != -1)
                {
                    int code;
                    if (hashOnData)
                    {
                        int off   = bytesStart[e0];
                        int start = off & ByteBlockPool.BYTE_BLOCK_MASK;
                        var bytes = pool.Buffers[off >> ByteBlockPool.BYTE_BLOCK_SHIFT];
                        int len;
                        int pos;
                        if ((bytes[start] & 0x80) == 0)
                        {
                            // length is 1 byte
                            len = bytes[start];
                            pos = start + 1;
                        }
                        else
                        {
                            len = (bytes[start] & 0x7f) + ((bytes[start + 1] & 0xff) << 7);
                            pos = start + 2;
                        }
                        code = DoHash(bytes, pos, len);
                    }
                    else
                    {
                        code = bytesStart[e0];
                    }

                    int hashPos = code & newMask;
                    if (Debugging.AssertsEnabled)
                    {
                        Debugging.Assert(hashPos >= 0);
                    }
                    if (newHash[hashPos] != -1)
                    {
                        // Conflict; use linear probe to find an open slot
                        // (see LUCENE-5604):
                        do
                        {
                            code++;
                            hashPos = code & newMask;
                        } while (newHash[hashPos] != -1);
                    }
                    newHash[hashPos] = e0;
                }
            }

            hashMask = newMask;
            bytesUsed.AddAndGet(RamUsageEstimator.NUM_BYTES_INT32 * (-ids.Length));
            ids          = newHash;
            hashSize     = newSize;
            hashHalfSize = newSize / 2;
        }
Ejemplo n.º 4
0
        /// <summary>
        /// Compute union of two sets of integers represented as sorted arrays.
        /// </summary>
        /// <param name="lhs"> a set of integers, represented as a sorted array. </param>
        /// <param name="rhs"> a set of integers, represented as a sorted array. </param>
        /// <returns> a set of integers, represented as a sorted array. </returns>
        // NOTE: this implementation was measured to be faster than an implementation
        // with countUnique for arrays on size 100+.
        public static int[] Union(int[] lhs, int[] rhs)
        {
            if (lhs == null || rhs == null)
            {
                return(lhs == null ? rhs : lhs);
            }

            Debug.Assert(IsSortedSet(lhs) && IsSortedSet(rhs));
            if (lhs.Length < rhs.Length)
            {
                return(Union(rhs, lhs));
            }
            int[] merged = null;
            int   m      = 0;
            int   l      = 0;

            for (int r = 0; l <= lhs.Length && r < rhs.Length;)
            {
                while (l < lhs.Length && lhs[l] < rhs[r])
                {
                    if (merged != null)
                    {
                        merged[m++] = lhs[l];
                    }
                    l++;
                }
                if (l == lhs.Length)
                {
                    if (merged == null)
                    {
                        merged = Arrays.copyOf(lhs, lhs.Length + rhs.Length - r);
                        m      = l;
                    }
                    Array.Copy(rhs, r, merged, m, rhs.Length - r);
                    m += rhs.Length - r;
                    break;
                }
                if (lhs[l] > rhs[r])
                {
                    if (merged == null)
                    {
                        merged = Arrays.copyOf(lhs, lhs.Length + rhs.Length - r);
                        m      = l;
                    }
                    merged[m++] = rhs[r++];
                }
                else                         // i.e. ( lhs[l] == rhs[r] )
                {
                    if (merged != null)
                    {
                        merged[m++] = lhs[l];
                    }
                    l++;
                    r++;
                }
            }
            if (merged == null)
            {
                return(lhs);
            }
            if (l < lhs.Length)                 // get tail of lhs
            {
                Array.Copy(lhs, l, merged, m, lhs.Length - l);
                m += lhs.Length - l;
            }
            if (m < merged.Length)                 // truncate extra elements
            {
                merged = Arrays.copyOf(merged, m);
            }
            return(merged);
        }
Ejemplo n.º 5
0
        protected virtual void ProcessServerHello(ClientHandshakeState state, byte[] body)
        {
            SecurityParameters securityParameters = state.clientContext.SecurityParameters;

            MemoryStream buf = new MemoryStream(body, false);

            {
                ProtocolVersion server_version = TlsUtilities.ReadVersion(buf);
                ReportServerVersion(state, server_version);
            }

            securityParameters.serverRandom = TlsUtilities.ReadFully(32, buf);

            state.selectedSessionID = TlsUtilities.ReadOpaque8(buf);
            if (state.selectedSessionID.Length > 32)
            {
                throw new TlsFatalAlert(AlertDescription.illegal_parameter);
            }
            state.client.NotifySessionID(state.selectedSessionID);
            state.resumedSession = state.selectedSessionID.Length > 0 && state.tlsSession != null &&
                                   Arrays.AreEqual(state.selectedSessionID, state.tlsSession.SessionID);

            int selectedCipherSuite = TlsUtilities.ReadUint16(buf);

            if (!Arrays.Contains(state.offeredCipherSuites, selectedCipherSuite) ||
                selectedCipherSuite == CipherSuite.TLS_NULL_WITH_NULL_NULL ||
                CipherSuite.IsScsv(selectedCipherSuite) ||
                !TlsUtilities.IsValidCipherSuiteForVersion(selectedCipherSuite, state.clientContext.ServerVersion))
            {
                throw new TlsFatalAlert(AlertDescription.illegal_parameter);
            }
            ValidateSelectedCipherSuite(selectedCipherSuite, AlertDescription.illegal_parameter);
            state.client.NotifySelectedCipherSuite(selectedCipherSuite);

            byte selectedCompressionMethod = TlsUtilities.ReadUint8(buf);

            if (!Arrays.Contains(state.offeredCompressionMethods, selectedCompressionMethod))
            {
                throw new TlsFatalAlert(AlertDescription.illegal_parameter);
            }
            state.client.NotifySelectedCompressionMethod(selectedCompressionMethod);

            /*
             * RFC3546 2.2 The extended server hello message format MAY be sent in place of the server
             * hello message when the client has requested extended functionality via the extended
             * client hello message specified in Section 2.1. ... Note that the extended server hello
             * message is only sent in response to an extended client hello message. This prevents the
             * possibility that the extended server hello message could "break" existing TLS 1.0
             * clients.
             */

            /*
             * TODO RFC 3546 2.3 If [...] the older session is resumed, then the server MUST ignore
             * extensions appearing in the client hello, and send a server hello containing no
             * extensions.
             */

            // Integer -> byte[]
            state.serverExtensions = TlsProtocol.ReadExtensions(buf);

            /*
             * RFC 3546 2.2 Note that the extended server hello message is only sent in response to an
             * extended client hello message. However, see RFC 5746 exception below. We always include
             * the SCSV, so an Extended Server Hello is always allowed.
             */
            if (state.serverExtensions != null)
            {
                foreach (int extType in state.serverExtensions.Keys)
                {
                    /*
                     * RFC 5746 3.6. Note that sending a "renegotiation_info" extension in response to a
                     * ClientHello containing only the SCSV is an explicit exception to the prohibition
                     * in RFC 5246, Section 7.4.1.4, on the server sending unsolicited extensions and is
                     * only allowed because the client is signaling its willingness to receive the
                     * extension via the TLS_EMPTY_RENEGOTIATION_INFO_SCSV SCSV.
                     */
                    if (extType == ExtensionType.renegotiation_info)
                    {
                        continue;
                    }

                    /*
                     * RFC 5246 7.4.1.4 An extension type MUST NOT appear in the ServerHello unless the
                     * same extension type appeared in the corresponding ClientHello. If a client
                     * receives an extension type in ServerHello that it did not request in the
                     * associated ClientHello, it MUST abort the handshake with an unsupported_extension
                     * fatal alert.
                     */
                    if (null == TlsUtilities.GetExtensionData(state.clientExtensions, extType))
                    {
                        throw new TlsFatalAlert(AlertDescription.unsupported_extension);
                    }

                    /*
                     * RFC 3546 2.3. If [...] the older session is resumed, then the server MUST ignore
                     * extensions appearing in the client hello, and send a server hello containing no
                     * extensions[.]
                     */
                    if (state.resumedSession)
                    {
                        // TODO[compat-gnutls] GnuTLS test server sends server extensions e.g. ec_point_formats
                        // TODO[compat-openssl] OpenSSL test server sends server extensions e.g. ec_point_formats
                        // TODO[compat-polarssl] PolarSSL test server sends server extensions e.g. ec_point_formats
                        //throw new TlsFatalAlert(AlertDescription.illegal_parameter);
                    }
                }
            }

            /*
             * RFC 5746 3.4. Client Behavior: Initial Handshake
             */
            {
                /*
                 * When a ServerHello is received, the client MUST check if it includes the
                 * "renegotiation_info" extension:
                 */
                byte[] renegExtData = TlsUtilities.GetExtensionData(state.serverExtensions, ExtensionType.renegotiation_info);
                if (renegExtData != null)
                {
                    /*
                     * If the extension is present, set the secure_renegotiation flag to TRUE. The
                     * client MUST then verify that the length of the "renegotiated_connection"
                     * field is zero, and if it is not, MUST abort the handshake (by sending a fatal
                     * handshake_failure alert).
                     */
                    state.secure_renegotiation = true;

                    if (!Arrays.ConstantTimeAreEqual(renegExtData, TlsProtocol.CreateRenegotiationInfo(TlsUtilities.EmptyBytes)))
                    {
                        throw new TlsFatalAlert(AlertDescription.handshake_failure);
                    }
                }
            }

            // TODO[compat-gnutls] GnuTLS test server fails to send renegotiation_info extension when resuming
            state.client.NotifySecureRenegotiation(state.secure_renegotiation);

            IDictionary sessionClientExtensions = state.clientExtensions, sessionServerExtensions = state.serverExtensions;

            if (state.resumedSession)
            {
                if (selectedCipherSuite != state.sessionParameters.CipherSuite ||
                    selectedCompressionMethod != state.sessionParameters.CompressionAlgorithm)
                {
                    throw new TlsFatalAlert(AlertDescription.illegal_parameter);
                }

                sessionClientExtensions = null;
                sessionServerExtensions = state.sessionParameters.ReadServerExtensions();
            }

            securityParameters.cipherSuite          = selectedCipherSuite;
            securityParameters.compressionAlgorithm = selectedCompressionMethod;

            if (sessionServerExtensions != null)
            {
                {
                    /*
                     * RFC 7366 3. If a server receives an encrypt-then-MAC request extension from a client
                     * and then selects a stream or Authenticated Encryption with Associated Data (AEAD)
                     * ciphersuite, it MUST NOT send an encrypt-then-MAC response extension back to the
                     * client.
                     */
                    bool serverSentEncryptThenMAC = TlsExtensionsUtilities.HasEncryptThenMacExtension(sessionServerExtensions);
                    if (serverSentEncryptThenMAC && !TlsUtilities.IsBlockCipherSuite(securityParameters.CipherSuite))
                    {
                        throw new TlsFatalAlert(AlertDescription.illegal_parameter);
                    }
                    securityParameters.encryptThenMac = serverSentEncryptThenMAC;
                }

                securityParameters.extendedMasterSecret = TlsExtensionsUtilities.HasExtendedMasterSecretExtension(sessionServerExtensions);

                securityParameters.maxFragmentLength = EvaluateMaxFragmentLengthExtension(state.resumedSession,
                                                                                          sessionClientExtensions, sessionServerExtensions, AlertDescription.illegal_parameter);

                securityParameters.truncatedHMac = TlsExtensionsUtilities.HasTruncatedHMacExtension(sessionServerExtensions);

                /*
                 * TODO It's surprising that there's no provision to allow a 'fresh' CertificateStatus to be
                 * sent in a session resumption handshake.
                 */
                state.allowCertificateStatus = !state.resumedSession &&
                                               TlsUtilities.HasExpectedEmptyExtensionData(sessionServerExtensions, ExtensionType.status_request,
                                                                                          AlertDescription.illegal_parameter);

                state.expectSessionTicket = !state.resumedSession &&
                                            TlsUtilities.HasExpectedEmptyExtensionData(sessionServerExtensions, ExtensionType.session_ticket,
                                                                                       AlertDescription.illegal_parameter);
            }

            /*
             * TODO[session-hash]
             *
             * draft-ietf-tls-session-hash-04 4. Clients and servers SHOULD NOT accept handshakes
             * that do not use the extended master secret [..]. (and see 5.2, 5.3)
             */

            if (sessionClientExtensions != null)
            {
                state.client.ProcessServerExtensions(sessionServerExtensions);
            }

            securityParameters.prfAlgorithm = TlsProtocol.GetPrfAlgorithm(state.clientContext,
                                                                          securityParameters.CipherSuite);

            /*
             * RFC 5264 7.4.9. Any cipher suite which does not explicitly specify verify_data_length has
             * a verify_data_length equal to 12. This includes all existing cipher suites.
             */
            securityParameters.verifyDataLength = 12;
        }
Ejemplo n.º 6
0
 protected override int Asn1GetHashCode()
 {
     return(Arrays.GetHashCode(bytes));
 }
Ejemplo n.º 7
0
        public int DoFinal(byte[] output, int outOff)
        {
            if (totalLength == 0)
            {
                InitCipher();
            }

            int extra = bufOff;

            if (forEncryption)
            {
                Check.OutputLength(output, outOff, extra + macSize, "Output buffer too short");
            }
            else
            {
                if (extra < macSize)
                {
                    throw new InvalidCipherTextException("data too short");
                }

                extra -= macSize;

                Check.OutputLength(output, outOff, extra, "Output buffer too short");
            }

            if (extra > 0)
            {
                gCTRPartial(bufBlock, 0, extra, output, outOff);
            }

            atLength += (uint)atBlockPos;

            if (atLength > atLengthPre)
            {
                /*
                 *  Some AAD was sent after the cipher started. We determine the difference b/w the hash value
                 *  we actually used when the cipher started (S_atPre) and the final hash value calculated (S_at).
                 *  Then we carry this difference forward by multiplying by H^c, where c is the number of (full or
                 *  partial) cipher-text blocks produced, and adjust the current hash.
                 */

                // Finish hash for partial AAD block
                if (atBlockPos > 0)
                {
                    gHASHPartial(S_at, atBlock, 0, atBlockPos);
                }

                // Find the difference between the AAD hashes
                if (atLengthPre > 0)
                {
                    GcmUtilities.Xor(S_at, S_atPre);
                }

                // Number of cipher-text blocks produced
                long c = (long)(((totalLength * 8) + 127) >> 7);

                // Calculate the adjustment factor
                byte[] H_c = new byte[16];
                if (exp == null)
                {
                    exp = new Tables1kGcmExponentiator();
                    exp.Init(H);
                }
                exp.ExponentiateX(c, H_c);

                // Carry the difference forward
                GcmUtilities.Multiply(S_at, H_c);

                // Adjust the current hash
                GcmUtilities.Xor(S, S_at);
            }

            // Final gHASH
            byte[] X = new byte[BlockSize];
            Pack.UInt64_To_BE(atLength * 8UL, X, 0);
            Pack.UInt64_To_BE(totalLength * 8UL, X, 8);

            gHASHBlock(S, X);

            // T = MSBt(GCTRk(J0,S))
            byte[] tag = new byte[BlockSize];
            cipher.ProcessBlock(J0, 0, tag, 0);
            GcmUtilities.Xor(tag, S);

            int resultLen = extra;

            // We place into macBlock our calculated value for T
            this.macBlock = new byte[macSize];
            Array.Copy(tag, 0, macBlock, 0, macSize);

            if (forEncryption)
            {
                // Append T to the message
                Array.Copy(macBlock, 0, output, outOff + bufOff, macSize);
                resultLen += macSize;
            }
            else
            {
                // Retrieve the T value from the message and compare to calculated one
                byte[] msgMac = new byte[macSize];
                Array.Copy(bufBlock, extra, msgMac, 0, macSize);
                if (!Arrays.ConstantTimeAreEqual(this.macBlock, msgMac))
                {
                    throw new InvalidCipherTextException("mac check in GCM failed");
                }
            }

            Reset(false);

            return(resultLen);
        }
Ejemplo n.º 8
0
 public Ed448Signer(byte[] context)
 {
     this.context = Arrays.Clone(context);
 }
Ejemplo n.º 9
0
        private void ProcessHandshakeMessage(HandshakeType type, byte[] buf)
        {
            MemoryStream inStr = new MemoryStream(buf, false);

            /*
             * Check the type.
             */
            switch (type)
            {
            case HandshakeType.certificate:
            {
                switch (connection_state)
                {
                case CS_SERVER_HELLO_RECEIVED:
                {
                    // Parse the Certificate message and send to cipher suite

                    Certificate serverCertificate = Certificate.Parse(inStr);

                    AssertEmpty(inStr);

                    this.keyExchange.ProcessServerCertificate(serverCertificate);

                    this.authentication = tlsClient.GetAuthentication();
                    this.authentication.NotifyServerCertificate(serverCertificate);

                    break;
                }

                default:
                    this.FailWithError(AlertLevel.fatal, AlertDescription.unexpected_message);
                    break;
                }

                connection_state = CS_SERVER_CERTIFICATE_RECEIVED;
                break;
            }

            case HandshakeType.finished:
                switch (connection_state)
                {
                case CS_SERVER_CHANGE_CIPHER_SPEC_RECEIVED:
                    /*
                     * Read the checksum from the finished message, it has always 12 bytes.
                     */
                    byte[] serverVerifyData = new byte[12];
                    TlsUtilities.ReadFully(serverVerifyData, inStr);

                    AssertEmpty(inStr);

                    /*
                     * Calculate our own checksum.
                     */
                    byte[] expectedServerVerifyData = TlsUtilities.PRF(
                        securityParameters.masterSecret, "server finished",
                        rs.GetCurrentHash(), 12);

                    /*
                     * Compare both checksums.
                     */
                    if (!Arrays.ConstantTimeAreEqual(expectedServerVerifyData, serverVerifyData))
                    {
                        /*
                         * Wrong checksum in the finished message.
                         */
                        this.FailWithError(AlertLevel.fatal, AlertDescription.handshake_failure);
                    }

                    connection_state = CS_DONE;

                    /*
                     * We are now ready to receive application data.
                     */
                    this.appDataReady = true;
                    break;

                default:
                    this.FailWithError(AlertLevel.fatal, AlertDescription.unexpected_message);
                    break;
                }
                break;

            case HandshakeType.server_hello:
                switch (connection_state)
                {
                case CS_CLIENT_HELLO_SEND:
                    /*
                     * Read the server hello message
                     */
                    TlsUtilities.CheckVersion(inStr, this);

                    /*
                     * Read the server random
                     */
                    securityParameters.serverRandom = new byte[32];
                    TlsUtilities.ReadFully(securityParameters.serverRandom, inStr);

                    byte[] sessionID = TlsUtilities.ReadOpaque8(inStr);
                    if (sessionID.Length > 32)
                    {
                        this.FailWithError(AlertLevel.fatal, AlertDescription.illegal_parameter);
                    }

                    this.tlsClient.NotifySessionID(sessionID);

                    /*
                     * Find out which CipherSuite the server has chosen and check that
                     * it was one of the offered ones.
                     */
                    CipherSuite selectedCipherSuite = (CipherSuite)TlsUtilities.ReadUint16(inStr);
                    if (!ArrayContains(offeredCipherSuites, selectedCipherSuite) ||
                        selectedCipherSuite == CipherSuite.TLS_EMPTY_RENEGOTIATION_INFO_SCSV)
                    {
                        this.FailWithError(AlertLevel.fatal, AlertDescription.illegal_parameter);
                    }

                    this.tlsClient.NotifySelectedCipherSuite(selectedCipherSuite);

                    /*
                     * Find out which CompressionMethod the server has chosen and check that
                     * it was one of the offered ones.
                     */
                    CompressionMethod selectedCompressionMethod = (CompressionMethod)TlsUtilities.ReadUint8(inStr);
                    if (!ArrayContains(offeredCompressionMethods, selectedCompressionMethod))
                    {
                        this.FailWithError(AlertLevel.fatal, AlertDescription.illegal_parameter);
                    }

                    this.tlsClient.NotifySelectedCompressionMethod(selectedCompressionMethod);

                    /*
                     * RFC3546 2.2 The extended server hello message format MAY be
                     * sent in place of the server hello message when the client has
                     * requested extended functionality via the extended client hello
                     * message specified in Section 2.1.
                     * ...
                     * Note that the extended server hello message is only sent in response
                     * to an extended client hello message.  This prevents the possibility
                     * that the extended server hello message could "break" existing TLS 1.0
                     * clients.
                     */

                    /*
                     * TODO RFC 3546 2.3
                     * If [...] the older session is resumed, then the server MUST ignore
                     * extensions appearing in the client hello, and send a server hello
                     * containing no extensions.
                     */

                    // ExtensionType -> byte[]
                    IDictionary serverExtensions = Platform.CreateHashtable();

                    if (inStr.Position < inStr.Length)
                    {
                        // Process extensions from extended server hello
                        byte[] extBytes = TlsUtilities.ReadOpaque16(inStr);

                        MemoryStream ext = new MemoryStream(extBytes, false);
                        while (ext.Position < ext.Length)
                        {
                            ExtensionType extType  = (ExtensionType)TlsUtilities.ReadUint16(ext);
                            byte[]        extValue = TlsUtilities.ReadOpaque16(ext);

                            // Note: RFC 5746 makes a special case for EXT_RenegotiationInfo
                            if (extType != ExtensionType.renegotiation_info &&
                                !clientExtensions.Contains(extType))
                            {
                                /*
                                 * RFC 3546 2.3
                                 * Note that for all extension types (including those defined in
                                 * future), the extension type MUST NOT appear in the extended server
                                 * hello unless the same extension type appeared in the corresponding
                                 * client hello.  Thus clients MUST abort the handshake if they receive
                                 * an extension type in the extended server hello that they did not
                                 * request in the associated (extended) client hello.
                                 */
                                this.FailWithError(AlertLevel.fatal, AlertDescription.unsupported_extension);
                            }

                            if (serverExtensions.Contains(extType))
                            {
                                /*
                                 * RFC 3546 2.3
                                 * Also note that when multiple extensions of different types are
                                 * present in the extended client hello or the extended server hello,
                                 * the extensions may appear in any order. There MUST NOT be more than
                                 * one extension of the same type.
                                 */
                                this.FailWithError(AlertLevel.fatal, AlertDescription.illegal_parameter);
                            }

                            serverExtensions.Add(extType, extValue);
                        }
                    }

                    AssertEmpty(inStr);

                    /*
                     * RFC 5746 3.4. When a ServerHello is received, the client MUST check if it
                     * includes the "renegotiation_info" extension:
                     */
                    {
                        bool secure_negotiation = serverExtensions.Contains(ExtensionType.renegotiation_info);

                        /*
                         * If the extension is present, set the secure_renegotiation flag
                         * to TRUE.  The client MUST then verify that the length of the
                         * "renegotiated_connection" field is zero, and if it is not, MUST
                         * abort the handshake (by sending a fatal handshake_failure
                         * alert).
                         */
                        if (secure_negotiation)
                        {
                            byte[] renegExtValue = (byte[])serverExtensions[ExtensionType.renegotiation_info];

                            if (!Arrays.ConstantTimeAreEqual(renegExtValue,
                                                             CreateRenegotiationInfo(emptybuf)))
                            {
                                this.FailWithError(AlertLevel.fatal, AlertDescription.handshake_failure);
                            }
                        }

                        tlsClient.NotifySecureRenegotiation(secure_negotiation);
                    }

                    if (clientExtensions != null)
                    {
                        tlsClient.ProcessServerExtensions(serverExtensions);
                    }

                    this.keyExchange = tlsClient.GetKeyExchange();

                    connection_state = CS_SERVER_HELLO_RECEIVED;
                    break;

                default:
                    this.FailWithError(AlertLevel.fatal, AlertDescription.unexpected_message);
                    break;
                }
                break;

            case HandshakeType.server_hello_done:
                switch (connection_state)
                {
                case CS_SERVER_CERTIFICATE_RECEIVED:
                case CS_SERVER_KEY_EXCHANGE_RECEIVED:
                case CS_CERTIFICATE_REQUEST_RECEIVED:

                    // NB: Original code used case label fall-through
                    if (connection_state == CS_SERVER_CERTIFICATE_RECEIVED)
                    {
                        // There was no server key exchange message; check it's OK
                        this.keyExchange.SkipServerKeyExchange();
                    }

                    AssertEmpty(inStr);

                    connection_state = CS_SERVER_HELLO_DONE_RECEIVED;

                    TlsCredentials clientCreds = null;
                    if (certificateRequest == null)
                    {
                        this.keyExchange.SkipClientCredentials();
                    }
                    else
                    {
                        clientCreds = this.authentication.GetClientCredentials(certificateRequest);

                        Certificate clientCert;
                        if (clientCreds == null)
                        {
                            this.keyExchange.SkipClientCredentials();
                            clientCert = Certificate.EmptyChain;
                        }
                        else
                        {
                            this.keyExchange.ProcessClientCredentials(clientCreds);
                            clientCert = clientCreds.Certificate;
                        }

                        SendClientCertificate(clientCert);
                    }

                    /*
                     * Send the client key exchange message, depending on the key
                     * exchange we are using in our CipherSuite.
                     */
                    SendClientKeyExchange();

                    connection_state = CS_CLIENT_KEY_EXCHANGE_SEND;

                    if (clientCreds != null && clientCreds is TlsSignerCredentials)
                    {
                        TlsSignerCredentials signerCreds = (TlsSignerCredentials)clientCreds;
                        byte[] md5andsha1 = rs.GetCurrentHash();
                        byte[] clientCertificateSignature = signerCreds.GenerateCertificateSignature(
                            md5andsha1);
                        SendCertificateVerify(clientCertificateSignature);

                        connection_state = CS_CERTIFICATE_VERIFY_SEND;
                    }

                    /*
                     * Now, we send change cipher state
                     */
                    byte[] cmessage = new byte[1];
                    cmessage[0] = 1;
                    rs.WriteMessage(ContentType.change_cipher_spec, cmessage, 0, cmessage.Length);

                    connection_state = CS_CLIENT_CHANGE_CIPHER_SPEC_SEND;

                    /*
                     * Calculate the master_secret
                     */
                    byte[] pms = this.keyExchange.GeneratePremasterSecret();

                    securityParameters.masterSecret = TlsUtilities.PRF(pms, "master secret",
                                                                       TlsUtilities.Concat(securityParameters.clientRandom, securityParameters.serverRandom),
                                                                       48);

                    // TODO Is there a way to ensure the data is really overwritten?

                    /*
                     * RFC 2246 8.1. The pre_master_secret should be deleted from
                     * memory once the master_secret has been computed.
                     */
                    Array.Clear(pms, 0, pms.Length);

                    /*
                     * Initialize our cipher suite
                     */
                    rs.ClientCipherSpecDecided(tlsClient.GetCompression(), tlsClient.GetCipher());

                    /*
                     * Send our finished message.
                     */
                    byte[] clientVerifyData = TlsUtilities.PRF(securityParameters.masterSecret,
                                                               "client finished", rs.GetCurrentHash(), 12);

                    MemoryStream bos = new MemoryStream();
                    TlsUtilities.WriteUint8((byte)HandshakeType.finished, bos);
                    TlsUtilities.WriteOpaque24(clientVerifyData, bos);
                    byte[] message = bos.ToArray();

                    rs.WriteMessage(ContentType.handshake, message, 0, message.Length);

                    this.connection_state = CS_CLIENT_FINISHED_SEND;
                    break;

                default:
                    this.FailWithError(AlertLevel.fatal, AlertDescription.handshake_failure);
                    break;
                }
                break;

            case HandshakeType.server_key_exchange:
            {
                switch (connection_state)
                {
                case CS_SERVER_HELLO_RECEIVED:
                case CS_SERVER_CERTIFICATE_RECEIVED:
                {
                    // NB: Original code used case label fall-through
                    if (connection_state == CS_SERVER_HELLO_RECEIVED)
                    {
                        // There was no server certificate message; check it's OK
                        this.keyExchange.SkipServerCertificate();
                        this.authentication = null;
                    }

                    this.keyExchange.ProcessServerKeyExchange(inStr);

                    AssertEmpty(inStr);
                    break;
                }

                default:
                    this.FailWithError(AlertLevel.fatal, AlertDescription.unexpected_message);
                    break;
                }

                this.connection_state = CS_SERVER_KEY_EXCHANGE_RECEIVED;
                break;
            }

            case HandshakeType.certificate_request:
                switch (connection_state)
                {
                case CS_SERVER_CERTIFICATE_RECEIVED:
                case CS_SERVER_KEY_EXCHANGE_RECEIVED:
                {
                    // NB: Original code used case label fall-through
                    if (connection_state == CS_SERVER_CERTIFICATE_RECEIVED)
                    {
                        // There was no server key exchange message; check it's OK
                        this.keyExchange.SkipServerKeyExchange();
                    }

                    if (this.authentication == null)
                    {
                        /*
                         * RFC 2246 7.4.4. It is a fatal handshake_failure alert
                         * for an anonymous server to request client identification.
                         */
                        this.FailWithError(AlertLevel.fatal, AlertDescription.handshake_failure);
                    }

                    int numTypes = TlsUtilities.ReadUint8(inStr);
                    ClientCertificateType[] certificateTypes = new ClientCertificateType[numTypes];
                    for (int i = 0; i < numTypes; ++i)
                    {
                        certificateTypes[i] = (ClientCertificateType)TlsUtilities.ReadUint8(inStr);
                    }

                    byte[] authorities = TlsUtilities.ReadOpaque16(inStr);

                    AssertEmpty(inStr);

                    IList authorityDNs = Platform.CreateArrayList();

                    MemoryStream bis = new MemoryStream(authorities, false);
                    while (bis.Position < bis.Length)
                    {
                        byte[] dnBytes = TlsUtilities.ReadOpaque16(bis);
                        // TODO Switch to X500Name when available
                        authorityDNs.Add(X509Name.GetInstance(Asn1Object.FromByteArray(dnBytes)));
                    }

                    this.certificateRequest = new CertificateRequest(certificateTypes,
                                                                     authorityDNs);
                    this.keyExchange.ValidateCertificateRequest(this.certificateRequest);

                    break;
                }

                default:
                    this.FailWithError(AlertLevel.fatal, AlertDescription.unexpected_message);
                    break;
                }

                this.connection_state = CS_CERTIFICATE_REQUEST_RECEIVED;
                break;

            case HandshakeType.hello_request:
                /*
                 * RFC 2246 7.4.1.1 Hello request
                 * This message will be ignored by the client if the client is currently
                 * negotiating a session. This message may be ignored by the client if it
                 * does not wish to renegotiate a session, or the client may, if it wishes,
                 * respond with a no_renegotiation alert.
                 */
                if (connection_state == CS_DONE)
                {
                    // Renegotiation not supported yet
                    SendAlert(AlertLevel.warning, AlertDescription.no_renegotiation);
                }
                break;

            case HandshakeType.client_key_exchange:
            case HandshakeType.certificate_verify:
            case HandshakeType.client_hello:
            default:
                // We do not support this!
                this.FailWithError(AlertLevel.fatal, AlertDescription.unexpected_message);
                break;
            }
        }
Ejemplo n.º 10
0
 /// <summary>
 /// Create a new parameter set with a different IV.
 /// </summary>
 /// <returns>A copy of the current parameter set with the new IV.</returns>
 /// <param name="iv">The IV to use.</param>
 public TParam WithIV(byte[] iv)
 {
     return(CreateParameter(Algorithm, Arrays.Clone(iv)));
 }
Ejemplo n.º 11
0
 public byte[] GetIV()
 {
     return(Arrays.Clone(iv));
 }
Ejemplo n.º 12
0
        private void encodeSideInfo2(LameGlobalFlags gfp, int bitsPerFrame)
        {
            var         gfc = gfp.internal_flags;
            IIISideInfo l3_side;
            int         gr, ch;

            l3_side = gfc.l3_side;
            gfc.header[gfc.h_ptr].ptr = 0;
            Arrays.Fill(gfc.header[gfc.h_ptr].buf, 0, gfc.sideinfo_len, (byte)0);
            if (gfp.out_samplerate < 16000)
            {
                writeheader(gfc, 0xffe, 12);
            }
            else
            {
                writeheader(gfc, 0xfff, 12);
            }

            writeheader(gfc, gfp.version, 1);
            writeheader(gfc, 4 - 3, 2);
            writeheader(gfc, !gfp.error_protection ? 1 : 0, 1);
            writeheader(gfc, gfc.bitrate_index, 4);
            writeheader(gfc, gfc.samplerate_index, 2);
            writeheader(gfc, gfc.padding, 1);
            writeheader(gfc, gfp.extension, 1);
            writeheader(gfc, (int)gfp.mode, 2);
            writeheader(gfc, gfc.mode_ext, 2);
            writeheader(gfc, gfp.copyright, 1);
            writeheader(gfc, gfp.original, 1);
            writeheader(gfc, gfp.emphasis, 2);
            if (gfp.error_protection)
            {
                writeheader(gfc, 0, 16); // dummy
            }
            if (gfp.version == 1)
            {
                /* MPEG1 */
                Debug.Assert(l3_side.main_data_begin >= 0);
                writeheader(gfc, l3_side.main_data_begin, 9);

                if (gfc.channels_out == 2)
                {
                    writeheader(gfc, l3_side.private_bits, 3);
                }
                else
                {
                    writeheader(gfc, l3_side.private_bits, 5);
                }

                for (ch = 0; ch < gfc.channels_out; ch++)
                {
                    int band;
                    for (band = 0; band < 4; band++)
                    {
                        writeheader(gfc, l3_side.scfsi[ch][band], 1);
                    }
                }

                for (gr = 0; gr < 2; gr++)
                {
                    for (ch = 0; ch < gfc.channels_out; ch++)
                    {
                        var gi = l3_side.tt[gr][ch];
                        writeheader(gfc, gi.part2_3_length + gi.part2_length, 12);
                        writeheader(gfc, gi.big_values / 2, 9);
                        writeheader(gfc, gi.global_gain, 8);
                        writeheader(gfc, gi.scalefac_compress, 4);

                        if (gi.block_type != Encoder.NORM_TYPE)
                        {
                            writeheader(gfc, 1, 1); // window_switching_flag
                            writeheader(gfc, gi.block_type, 2);
                            writeheader(gfc, gi.mixed_block_flag, 1);

                            if (gi.table_select[0] == 14)
                            {
                                gi.table_select[0] = 16;
                            }

                            writeheader(gfc, gi.table_select[0], 5);
                            if (gi.table_select[1] == 14)
                            {
                                gi.table_select[1] = 16;
                            }

                            writeheader(gfc, gi.table_select[1], 5);

                            writeheader(gfc, gi.subblock_gain[0], 3);
                            writeheader(gfc, gi.subblock_gain[1], 3);
                            writeheader(gfc, gi.subblock_gain[2], 3);
                        }
                        else
                        {
                            writeheader(gfc, 0, 1); // window_switching_flag
                            if (gi.table_select[0] == 14)
                            {
                                gi.table_select[0] = 16;
                            }

                            writeheader(gfc, gi.table_select[0], 5);
                            if (gi.table_select[1] == 14)
                            {
                                gi.table_select[1] = 16;
                            }

                            writeheader(gfc, gi.table_select[1], 5);
                            if (gi.table_select[2] == 14)
                            {
                                gi.table_select[2] = 16;
                            }

                            writeheader(gfc, gi.table_select[2], 5);

                            Debug.Assert(0 <= gi.region0_count && gi.region0_count < 16);
                            Debug.Assert(0 <= gi.region1_count && gi.region1_count < 8);
                            writeheader(gfc, gi.region0_count, 4);
                            writeheader(gfc, gi.region1_count, 3);
                        }

                        writeheader(gfc, gi.preflag, 1);
                        writeheader(gfc, gi.scalefac_scale, 1);
                        writeheader(gfc, gi.count1table_select, 1);
                    }
                }
            }
            else
            {
                /* MPEG2 */
                Debug.Assert(l3_side.main_data_begin >= 0);
                writeheader(gfc, l3_side.main_data_begin, 8);
                writeheader(gfc, l3_side.private_bits, gfc.channels_out);

                gr = 0;
                for (ch = 0; ch < gfc.channels_out; ch++)
                {
                    var gi = l3_side.tt[gr][ch];
                    writeheader(gfc, gi.part2_3_length + gi.part2_length, 12);
                    writeheader(gfc, gi.big_values / 2, 9);
                    writeheader(gfc, gi.global_gain, 8);
                    writeheader(gfc, gi.scalefac_compress, 9);

                    if (gi.block_type != Encoder.NORM_TYPE)
                    {
                        writeheader(gfc, 1, 1); // window_switching_flag
                        writeheader(gfc, gi.block_type, 2);
                        writeheader(gfc, gi.mixed_block_flag, 1);

                        if (gi.table_select[0] == 14)
                        {
                            gi.table_select[0] = 16;
                        }

                        writeheader(gfc, gi.table_select[0], 5);
                        if (gi.table_select[1] == 14)
                        {
                            gi.table_select[1] = 16;
                        }

                        writeheader(gfc, gi.table_select[1], 5);

                        writeheader(gfc, gi.subblock_gain[0], 3);
                        writeheader(gfc, gi.subblock_gain[1], 3);
                        writeheader(gfc, gi.subblock_gain[2], 3);
                    }
                    else
                    {
                        writeheader(gfc, 0, 1); // window_switching_flag
                        if (gi.table_select[0] == 14)
                        {
                            gi.table_select[0] = 16;
                        }

                        writeheader(gfc, gi.table_select[0], 5);
                        if (gi.table_select[1] == 14)
                        {
                            gi.table_select[1] = 16;
                        }

                        writeheader(gfc, gi.table_select[1], 5);
                        if (gi.table_select[2] == 14)
                        {
                            gi.table_select[2] = 16;
                        }

                        writeheader(gfc, gi.table_select[2], 5);

                        Debug.Assert(0 <= gi.region0_count && gi.region0_count < 16);
                        Debug.Assert(0 <= gi.region1_count && gi.region1_count < 8);
                        writeheader(gfc, gi.region0_count, 4);
                        writeheader(gfc, gi.region1_count, 3);
                    }

                    writeheader(gfc, gi.scalefac_scale, 1);
                    writeheader(gfc, gi.count1table_select, 1);
                }
            }

            if (gfp.error_protection)
            {
                CRC_writeheader(gfc, gfc.header[gfc.h_ptr].buf);
            }

            {
                var old = gfc.h_ptr;
                Debug.Assert(gfc.header[old].ptr == gfc.sideinfo_len * 8);

                gfc.h_ptr = (old + 1) & (LameInternalFlags.MAX_HEADER_BUF - 1);
                gfc.header[gfc.h_ptr].write_timing = gfc.header[old].write_timing + bitsPerFrame;

                if (gfc.h_ptr == gfc.w_ptr)
                {
                    Console.Error.WriteLine("Error: MAX_HEADER_BUF too small in bitstream.c \n");
                }
            }
        }
Ejemplo n.º 13
0
        /// <summary>
        ///     <PRE>
        ///         copy data out of the internal MP3 bit buffer into a user supplied
        ///         unsigned char buffer.
        ///         mp3data=0      indicates data in buffer is an id3tags and VBR tags
        ///         mp3data=1      data is real mp3 frame data.
        ///     </PRE>
        /// </summary>
        internal int copy_buffer(LameInternalFlags gfc, byte[] buffer, int bufferPos, int size, int mp3data)
        {
            var minimum = bufByteIdx + 1;

            if (minimum <= 0)
            {
                return(0);
            }

            if (size != 0 && minimum > size)
            {
                return(-1);
            }

            Array.Copy(buf, 0, buffer, bufferPos, minimum);
            bufByteIdx = -1;
            bufBitIdx  = 0;

            if (mp3data != 0)
            {
                var crc = new int[1];
                crc[0] = gfc.nMusicCRC;
                vbr.updateMusicCRC(crc, buffer, bufferPos, minimum);
                gfc.nMusicCRC = crc[0];

                /// <summary>
                /// sum number of bytes belonging to the mp3 stream this info will be
                /// written into the Xing/LAME header for seeking
                /// </summary>
                if (minimum > 0)
                {
                    gfc.VBR_seek_table.nBytesWritten += minimum;
                }

                if (gfc.decode_on_the_fly)
                {
                    // decode the frame

                    var pcm_buf     = Arrays.ReturnRectangularArray <float>(2, 1152);
                    var mp3_in      = minimum;
                    var samples_out = -1;
                    int i;

                    /* re-synthesis to pcm. Repeat until we get a samples_out=0 */
                    while (samples_out != 0)
                    {
                        samples_out = mpg.hip_decode1_unclipped(
                            gfc.hip,
                            buffer,
                            bufferPos,
                            mp3_in,
                            pcm_buf[0],
                            pcm_buf[1]);

                        /*
                         * samples_out = 0: need more data to decode samples_out =
                         * -1: error. Lets assume 0 pcm output samples_out = number
                         * of samples output
                         */

                        /*
                         * set the lenght of the mp3 input buffer to zero, so that
                         * in the next iteration of the loop we will be querying
                         * mpglib about buffered data
                         */
                        mp3_in = 0;

                        if (samples_out == -1)
                        {
                            samples_out = 0;
                        }

                        if (samples_out > 0)
                        {
                            /* process the PCM data */

                            /*
                             * this should not be possible, and indicates we have
                             * overflown the pcm_buf buffer
                             */
                            Debug.Assert(samples_out <= 1152);

                            if (gfc.findPeakSample)
                            {
                                for (i = 0; i < samples_out; i++)
                                {
                                    if (pcm_buf[0][i] > gfc.PeakSample)
                                    {
                                        gfc.PeakSample = pcm_buf[0][i];
                                    }
                                    else if (-pcm_buf[0][i] > gfc.PeakSample)
                                    {
                                        gfc.PeakSample = -pcm_buf[0][i];
                                    }
                                }

                                if (gfc.channels_out > 1)
                                {
                                    for (i = 0; i < samples_out; i++)
                                    {
                                        if (pcm_buf[1][i] > gfc.PeakSample)
                                        {
                                            gfc.PeakSample = pcm_buf[1][i];
                                        }
                                        else if (-pcm_buf[1][i] > gfc.PeakSample)
                                        {
                                            gfc.PeakSample = -pcm_buf[1][i];
                                        }
                                    }
                                }
                            }

                            if (gfc.findReplayGain)
                            {
                                if (ga.AnalyzeSamples(
                                        gfc.rgdata,
                                        pcm_buf[0],
                                        0,
                                        pcm_buf[1],
                                        0,
                                        samples_out,
                                        gfc.channels_out) == GainAnalysis.GAIN_ANALYSIS_ERROR)
                                {
                                    return(-6);
                                }
                            }
                        } // if (samples_out>0)
                    }     // while (samples_out!=0)
                }         // if (gfc.decode_on_the_fly)
            }             // if (mp3data)

            return(minimum);
        }
Ejemplo n.º 14
0
 /// <summary>The collectionAcceptFilter accepts a certain collection.</summary>
 public static IPredicate <E> CollectionAcceptFilter <E>(E[] objs)
 {
     return(new Filters.CollectionAcceptFilter <E>(Arrays.AsList(objs), true));
 }
Ejemplo n.º 15
0
 public ConjFilter(params IPredicate <T>[] filters)
 {
     this.filters = new List <IPredicate <T> >();
     Sharpen.Collections.AddAll(this.filters, Arrays.AsList(filters));
 }
Ejemplo n.º 16
0
 public void initInventory()
 {
     inventorySkills = new baseSkill[14];
     inventorySkills [0] = new Arrays ();
     inventorySkills [1] = new BreakAndContinue ();
     inventorySkills [2] = new DDOS ();
     inventorySkills [3] = new DefaultFunctions ();
     inventorySkills [4] = new FireWall ();
     inventorySkills [5] = new FunctionsWithInputOutput ();
     inventorySkills [6] = new FunctionsWithOutput ();
     inventorySkills [7] = new Hash ();
     inventorySkills [8] = new IfElse ();
     inventorySkills [9] = new InfiniteLoop ();
     inventorySkills [10] = new Loop ();
     inventorySkills [11] = new PacketSniffing ();
     inventorySkills [12] = new Recursion ();
     inventorySkills [13] = new Stack ();
     Debug.Log ("Finished Loading Inventory");
 }
 /**
  * @param key
  * @param checksum
  * @return
  * @see http://www.w3.org/TR/xmlenc-core/#sec-CMSKeyChecksum
  */
 private bool CheckCmsKeyChecksum(
     byte[]      key,
     byte[]      checksum)
 {
     return(Arrays.ConstantTimeAreEqual(CalculateCmsKeyChecksum(key), checksum));
 }
Ejemplo n.º 18
0
 private static RVFDatum <L, F> NewRVFDatum <L, F>(L label, params F[] items)
 {
     return(new RVFDatum <L, F>(Counters.AsCounter(Arrays.AsList(items)), label));
 }
Ejemplo n.º 19
0
 public virtual byte[] GetMac()
 {
     return(Arrays.Clone(macBlock));
 }
Ejemplo n.º 20
0
 /// <summary>
 /// Clears the <see cref="TermContext"/> internal state and removes all
 /// registered <see cref="TermState"/>s
 /// </summary>
 public void Clear()
 {
     docFreq = 0;
     Arrays.Fill(states, null);
 }
Ejemplo n.º 21
0
        /// <remarks>
        /// MAC sizes from 32 bits to 128 bits (must be a multiple of 8) are supported. The default is 128 bits.
        /// Sizes less than 96 are not recommended, but are supported for specialized applications.
        /// </remarks>
        public virtual void Init(
            bool forEncryption,
            ICipherParameters parameters)
        {
            this.forEncryption = forEncryption;
            this.macBlock      = null;

            KeyParameter keyParam;

            if (parameters is AeadParameters)
            {
                AeadParameters param = (AeadParameters)parameters;

                nonce = param.GetNonce();
                initialAssociatedText = param.GetAssociatedText();

                int macSizeBits = param.MacSize;
                if (macSizeBits < 32 || macSizeBits > 128 || macSizeBits % 8 != 0)
                {
                    throw new ArgumentException("Invalid value for MAC size: " + macSizeBits);
                }

                macSize  = macSizeBits / 8;
                keyParam = param.Key;
            }
            else if (parameters is ParametersWithIV)
            {
                ParametersWithIV param = (ParametersWithIV)parameters;

                nonce = param.GetIV();
                initialAssociatedText = null;
                macSize  = 16;
                keyParam = (KeyParameter)param.Parameters;
            }
            else
            {
                throw new ArgumentException("invalid parameters passed to GCM");
            }

            int bufLength = forEncryption ? BlockSize : (BlockSize + macSize);

            this.bufBlock = new byte[bufLength];

            if (nonce == null || nonce.Length < 1)
            {
                throw new ArgumentException("IV must be at least 1 byte");
            }

            // TODO Restrict macSize to 16 if nonce length not 12?

            // Cipher always used in forward mode
            // if keyParam is null we're reusing the last key.
            if (keyParam != null)
            {
                cipher.Init(true, keyParam);

                this.H = new byte[BlockSize];
                cipher.ProcessBlock(H, 0, H, 0);

                // if keyParam is null we're reusing the last key and the multiplier doesn't need re-init
                multiplier.Init(H);
                exp = null;
            }
            else if (this.H == null)
            {
                throw new ArgumentException("Key must be specified in initial init");
            }

            this.J0 = new byte[BlockSize];

            if (nonce.Length == 12)
            {
                Array.Copy(nonce, 0, J0, 0, nonce.Length);
                this.J0[BlockSize - 1] = 0x01;
            }
            else
            {
                gHASH(J0, nonce, nonce.Length);
                byte[] X = new byte[BlockSize];
                Pack.UInt64_To_BE((ulong)nonce.Length * 8UL, X, 8);
                gHASHBlock(J0, X);
            }

            this.S               = new byte[BlockSize];
            this.S_at            = new byte[BlockSize];
            this.S_atPre         = new byte[BlockSize];
            this.atBlock         = new byte[BlockSize];
            this.atBlockPos      = 0;
            this.atLength        = 0;
            this.atLengthPre     = 0;
            this.counter         = Arrays.Clone(J0);
            this.blocksRemaining = uint.MaxValue; // page 8, len(P) <= 2^39 - 256, 1 block used by tag
            this.bufOff          = 0;
            this.totalLength     = 0;

            if (initialAssociatedText != null)
            {
                ProcessAadBytes(initialAssociatedText, 0, initialAssociatedText.Length);
            }
        }
Ejemplo n.º 22
0
 public override int GetHashCode()
 {
     return(163763 ^ Arrays.GetHashCode(x, 0, 3));
 }
Ejemplo n.º 23
0
        protected virtual byte[] GenerateClientHello(ClientHandshakeState state, TlsClient client)
        {
            MemoryStream buf = new MemoryStream();

            ProtocolVersion client_version = client.ClientVersion;

            if (!client_version.IsDtls)
            {
                throw new TlsFatalAlert(AlertDescription.internal_error);
            }

            TlsClientContextImpl context = state.clientContext;

            context.SetClientVersion(client_version);
            TlsUtilities.WriteVersion(client_version, buf);

            SecurityParameters securityParameters = context.SecurityParameters;

            buf.Write(securityParameters.ClientRandom, 0, securityParameters.ClientRandom.Length);

            // Session ID
            byte[] session_id = TlsUtilities.EmptyBytes;
            if (state.tlsSession != null)
            {
                session_id = state.tlsSession.SessionID;
                if (session_id == null || session_id.Length > 32)
                {
                    session_id = TlsUtilities.EmptyBytes;
                }
            }
            TlsUtilities.WriteOpaque8(session_id, buf);

            // Cookie
            TlsUtilities.WriteOpaque8(TlsUtilities.EmptyBytes, buf);

            bool fallback = client.IsFallback;

            /*
             * Cipher suites
             */
            state.offeredCipherSuites = client.GetCipherSuites();

            // Integer -> byte[]
            state.clientExtensions = client.GetClientExtensions();

            // Cipher Suites (and SCSV)
            {
                /*
                 * RFC 5746 3.4. The client MUST include either an empty "renegotiation_info" extension,
                 * or the TLS_EMPTY_RENEGOTIATION_INFO_SCSV signaling cipher suite value in the
                 * ClientHello. Including both is NOT RECOMMENDED.
                 */
                byte[] renegExtData = TlsUtilities.GetExtensionData(state.clientExtensions, ExtensionType.renegotiation_info);
                bool   noRenegExt   = (null == renegExtData);

                bool noRenegSCSV = !Arrays.Contains(state.offeredCipherSuites, CipherSuite.TLS_EMPTY_RENEGOTIATION_INFO_SCSV);

                if (noRenegExt && noRenegSCSV)
                {
                    // TODO Consider whether to default to a client extension instead
                    state.offeredCipherSuites = Arrays.Append(state.offeredCipherSuites, CipherSuite.TLS_EMPTY_RENEGOTIATION_INFO_SCSV);
                }

                /*
                 * draft-ietf-tls-downgrade-scsv-00 4. If a client sends a ClientHello.client_version
                 * containing a lower value than the latest (highest-valued) version supported by the
                 * client, it SHOULD include the TLS_FALLBACK_SCSV cipher suite value in
                 * ClientHello.cipher_suites.
                 */
                if (fallback && !Arrays.Contains(state.offeredCipherSuites, CipherSuite.TLS_FALLBACK_SCSV))
                {
                    state.offeredCipherSuites = Arrays.Append(state.offeredCipherSuites, CipherSuite.TLS_FALLBACK_SCSV);
                }

                TlsUtilities.WriteUint16ArrayWithUint16Length(state.offeredCipherSuites, buf);
            }

            // TODO Add support for compression
            // Compression methods
            // state.offeredCompressionMethods = client.getCompressionMethods();
            state.offeredCompressionMethods = new byte[] { CompressionMethod.cls_null };

            TlsUtilities.WriteUint8ArrayWithUint8Length(state.offeredCompressionMethods, buf);

            // Extensions
            if (state.clientExtensions != null)
            {
                TlsProtocol.WriteExtensions(buf, state.clientExtensions);
            }

            return(buf.ToArray());
        }
Ejemplo n.º 24
0
        private static IndexReader[] PrepareSubReaders(CompositeReader[] readers, CompositeReader[] storedFieldsReaders)
        {
            if (readers.Length == 0)
            {
                if (storedFieldsReaders.Length > 0)
                {
                    throw new ArgumentException("There must be at least one main reader if storedFieldsReaders are used.");
                }
                // LUCENENET: Optimized empty string array creation
                return(Arrays.Empty <IndexReader>());
            }
            else
            {
                IList <IndexReader> firstSubReaders = readers[0].GetSequentialSubReaders();

                // check compatibility:
                int    maxDoc = readers[0].MaxDoc, noSubs = firstSubReaders.Count;
                int[]  childMaxDoc = new int[noSubs];
                bool[] childAtomic = new bool[noSubs];
                for (int i = 0; i < noSubs; i++)
                {
                    IndexReader r = firstSubReaders[i];
                    childMaxDoc[i] = r.MaxDoc;
                    childAtomic[i] = r is AtomicReader;
                }
                Validate(readers, maxDoc, childMaxDoc, childAtomic);
                Validate(storedFieldsReaders, maxDoc, childMaxDoc, childAtomic);

                // hierarchically build the same subreader structure as the first CompositeReader with Parallel*Readers:
                IndexReader[] subReaders = new IndexReader[noSubs];
                for (int i = 0; i < subReaders.Length; i++)
                {
                    if (firstSubReaders[i] is AtomicReader)
                    {
                        AtomicReader[] atomicSubs = new AtomicReader[readers.Length];
                        for (int j = 0; j < readers.Length; j++)
                        {
                            atomicSubs[j] = (AtomicReader)readers[j].GetSequentialSubReaders()[i];
                        }
                        AtomicReader[] storedSubs = new AtomicReader[storedFieldsReaders.Length];
                        for (int j = 0; j < storedFieldsReaders.Length; j++)
                        {
                            storedSubs[j] = (AtomicReader)storedFieldsReaders[j].GetSequentialSubReaders()[i];
                        }
                        // We pass true for closeSubs and we prevent closing of subreaders in doClose():
                        // By this the synthetic throw-away readers used here are completely invisible to ref-counting
                        subReaders[i] = new ParallelAtomicReaderAnonymousInnerClassHelper(atomicSubs, storedSubs);
                    }
                    else
                    {
                        Debug.Assert(firstSubReaders[i] is CompositeReader);
                        CompositeReader[] compositeSubs = new CompositeReader[readers.Length];
                        for (int j = 0; j < readers.Length; j++)
                        {
                            compositeSubs[j] = (CompositeReader)readers[j].GetSequentialSubReaders()[i];
                        }
                        CompositeReader[] storedSubs = new CompositeReader[storedFieldsReaders.Length];
                        for (int j = 0; j < storedFieldsReaders.Length; j++)
                        {
                            storedSubs[j] = (CompositeReader)storedFieldsReaders[j].GetSequentialSubReaders()[i];
                        }
                        // We pass true for closeSubs and we prevent closing of subreaders in doClose():
                        // By this the synthetic throw-away readers used here are completely invisible to ref-counting
                        subReaders[i] = new ParallelCompositeReaderAnonymousInnerClassHelper(compositeSubs, storedSubs);
                    }
                }
                return(subReaders);
            }
        }
Ejemplo n.º 25
0
        internal virtual DtlsTransport ClientHandshake(ClientHandshakeState state, DtlsRecordLayer recordLayer)
        {
            SecurityParameters    securityParameters = state.clientContext.SecurityParameters;
            DtlsReliableHandshake handshake          = new DtlsReliableHandshake(state.clientContext, recordLayer);

            byte[] clientHelloBody = GenerateClientHello(state, state.client);

            recordLayer.SetWriteVersion(ProtocolVersion.DTLSv10);

            handshake.SendMessage(HandshakeType.client_hello, clientHelloBody);

            DtlsReliableHandshake.Message serverMessage = handshake.ReceiveMessage();

            while (serverMessage.Type == HandshakeType.hello_verify_request)
            {
                ProtocolVersion recordLayerVersion = recordLayer.ReadVersion;
                ProtocolVersion client_version     = state.clientContext.ClientVersion;

                /*
                 * RFC 6347 4.2.1 DTLS 1.2 server implementations SHOULD use DTLS version 1.0 regardless of
                 * the version of TLS that is expected to be negotiated. DTLS 1.2 and 1.0 clients MUST use
                 * the version solely to indicate packet formatting (which is the same in both DTLS 1.2 and
                 * 1.0) and not as part of version negotiation.
                 */
                if (!recordLayerVersion.IsEqualOrEarlierVersionOf(client_version))
                {
                    throw new TlsFatalAlert(AlertDescription.illegal_parameter);
                }

                recordLayer.ReadVersion = null;

                byte[] cookie  = ProcessHelloVerifyRequest(state, serverMessage.Body);
                byte[] patched = PatchClientHelloWithCookie(clientHelloBody, cookie);

                handshake.ResetHandshakeMessagesDigest();
                handshake.SendMessage(HandshakeType.client_hello, patched);

                serverMessage = handshake.ReceiveMessage();
            }

            if (serverMessage.Type == HandshakeType.server_hello)
            {
                ProtocolVersion recordLayerVersion = recordLayer.ReadVersion;
                ReportServerVersion(state, recordLayerVersion);
                recordLayer.SetWriteVersion(recordLayerVersion);

                ProcessServerHello(state, serverMessage.Body);
            }
            else
            {
                throw new TlsFatalAlert(AlertDescription.unexpected_message);
            }

            handshake.NotifyHelloComplete();

            ApplyMaxFragmentLengthExtension(recordLayer, securityParameters.maxFragmentLength);

            if (state.resumedSession)
            {
                securityParameters.masterSecret = Arrays.Clone(state.sessionParameters.MasterSecret);
                recordLayer.InitPendingEpoch(state.client.GetCipher());

                // NOTE: Calculated exclusive of the actual Finished message from the server
                byte[] resExpectedServerVerifyData = TlsUtilities.CalculateVerifyData(state.clientContext, ExporterLabel.server_finished,
                                                                                      TlsProtocol.GetCurrentPrfHash(state.clientContext, handshake.HandshakeHash, null));
                ProcessFinished(handshake.ReceiveMessageBody(HandshakeType.finished), resExpectedServerVerifyData);

                // NOTE: Calculated exclusive of the Finished message itself
                byte[] resClientVerifyData = TlsUtilities.CalculateVerifyData(state.clientContext, ExporterLabel.client_finished,
                                                                              TlsProtocol.GetCurrentPrfHash(state.clientContext, handshake.HandshakeHash, null));
                handshake.SendMessage(HandshakeType.finished, resClientVerifyData);

                handshake.Finish();

                state.clientContext.SetResumableSession(state.tlsSession);

                state.client.NotifyHandshakeComplete();

                return(new DtlsTransport(recordLayer));
            }

            InvalidateSession(state);

            if (state.selectedSessionID.Length > 0)
            {
                state.tlsSession = new TlsSessionImpl(state.selectedSessionID, null);
            }

            serverMessage = handshake.ReceiveMessage();

            if (serverMessage.Type == HandshakeType.supplemental_data)
            {
                ProcessServerSupplementalData(state, serverMessage.Body);
                serverMessage = handshake.ReceiveMessage();
            }
            else
            {
                state.client.ProcessServerSupplementalData(null);
            }

            state.keyExchange = state.client.GetKeyExchange();
            state.keyExchange.Init(state.clientContext);

            Certificate serverCertificate = null;

            if (serverMessage.Type == HandshakeType.certificate)
            {
                serverCertificate = ProcessServerCertificate(state, serverMessage.Body);
                serverMessage     = handshake.ReceiveMessage();
            }
            else
            {
                // Okay, Certificate is optional
                state.keyExchange.SkipServerCredentials();
            }

            // TODO[RFC 3546] Check whether empty certificates is possible, allowed, or excludes CertificateStatus
            if (serverCertificate == null || serverCertificate.IsEmpty)
            {
                state.allowCertificateStatus = false;
            }

            if (serverMessage.Type == HandshakeType.certificate_status)
            {
                ProcessCertificateStatus(state, serverMessage.Body);
                serverMessage = handshake.ReceiveMessage();
            }
            else
            {
                // Okay, CertificateStatus is optional
            }

            if (serverMessage.Type == HandshakeType.server_key_exchange)
            {
                ProcessServerKeyExchange(state, serverMessage.Body);
                serverMessage = handshake.ReceiveMessage();
            }
            else
            {
                // Okay, ServerKeyExchange is optional
                state.keyExchange.SkipServerKeyExchange();
            }

            if (serverMessage.Type == HandshakeType.certificate_request)
            {
                ProcessCertificateRequest(state, serverMessage.Body);

                /*
                 * TODO Give the client a chance to immediately select the CertificateVerify hash
                 * algorithm here to avoid tracking the other hash algorithms unnecessarily?
                 */
                TlsUtilities.TrackHashAlgorithms(handshake.HandshakeHash,
                                                 state.certificateRequest.SupportedSignatureAlgorithms);

                serverMessage = handshake.ReceiveMessage();
            }
            else
            {
                // Okay, CertificateRequest is optional
            }

            if (serverMessage.Type == HandshakeType.server_hello_done)
            {
                if (serverMessage.Body.Length != 0)
                {
                    throw new TlsFatalAlert(AlertDescription.decode_error);
                }
            }
            else
            {
                throw new TlsFatalAlert(AlertDescription.unexpected_message);
            }

            handshake.HandshakeHash.SealHashAlgorithms();

            IList clientSupplementalData = state.client.GetClientSupplementalData();

            if (clientSupplementalData != null)
            {
                byte[] supplementalDataBody = GenerateSupplementalData(clientSupplementalData);
                handshake.SendMessage(HandshakeType.supplemental_data, supplementalDataBody);
            }

            if (state.certificateRequest != null)
            {
                state.clientCredentials = state.authentication.GetClientCredentials(state.certificateRequest);

                /*
                 * RFC 5246 If no suitable certificate is available, the client MUST send a certificate
                 * message containing no certificates.
                 *
                 * NOTE: In previous RFCs, this was SHOULD instead of MUST.
                 */
                Certificate clientCertificate = null;
                if (state.clientCredentials != null)
                {
                    clientCertificate = state.clientCredentials.Certificate;
                }
                if (clientCertificate == null)
                {
                    clientCertificate = Certificate.EmptyChain;
                }

                byte[] certificateBody = GenerateCertificate(clientCertificate);
                handshake.SendMessage(HandshakeType.certificate, certificateBody);
            }

            if (state.clientCredentials != null)
            {
                state.keyExchange.ProcessClientCredentials(state.clientCredentials);
            }
            else
            {
                state.keyExchange.SkipClientCredentials();
            }

            byte[] clientKeyExchangeBody = GenerateClientKeyExchange(state);
            handshake.SendMessage(HandshakeType.client_key_exchange, clientKeyExchangeBody);

            TlsHandshakeHash prepareFinishHash = handshake.PrepareToFinish();

            securityParameters.sessionHash = TlsProtocol.GetCurrentPrfHash(state.clientContext, prepareFinishHash, null);

            TlsProtocol.EstablishMasterSecret(state.clientContext, state.keyExchange);
            recordLayer.InitPendingEpoch(state.client.GetCipher());

            if (state.clientCredentials != null && state.clientCredentials is TlsSignerCredentials)
            {
                TlsSignerCredentials signerCredentials = (TlsSignerCredentials)state.clientCredentials;

                /*
                 * RFC 5246 4.7. digitally-signed element needs SignatureAndHashAlgorithm from TLS 1.2
                 */
                SignatureAndHashAlgorithm signatureAndHashAlgorithm = TlsUtilities.GetSignatureAndHashAlgorithm(
                    state.clientContext, signerCredentials);

                byte[] hash;
                if (signatureAndHashAlgorithm == null)
                {
                    hash = securityParameters.SessionHash;
                }
                else
                {
                    hash = prepareFinishHash.GetFinalHash(signatureAndHashAlgorithm.Hash);
                }

                byte[]          signature             = signerCredentials.GenerateCertificateSignature(hash);
                DigitallySigned certificateVerify     = new DigitallySigned(signatureAndHashAlgorithm, signature);
                byte[]          certificateVerifyBody = GenerateCertificateVerify(state, certificateVerify);
                handshake.SendMessage(HandshakeType.certificate_verify, certificateVerifyBody);
            }

            // NOTE: Calculated exclusive of the Finished message itself
            byte[] clientVerifyData = TlsUtilities.CalculateVerifyData(state.clientContext, ExporterLabel.client_finished,
                                                                       TlsProtocol.GetCurrentPrfHash(state.clientContext, handshake.HandshakeHash, null));
            handshake.SendMessage(HandshakeType.finished, clientVerifyData);

            if (state.expectSessionTicket)
            {
                serverMessage = handshake.ReceiveMessage();
                if (serverMessage.Type == HandshakeType.session_ticket)
                {
                    ProcessNewSessionTicket(state, serverMessage.Body);
                }
                else
                {
                    throw new TlsFatalAlert(AlertDescription.unexpected_message);
                }
            }

            // NOTE: Calculated exclusive of the actual Finished message from the server
            byte[] expectedServerVerifyData = TlsUtilities.CalculateVerifyData(state.clientContext, ExporterLabel.server_finished,
                                                                               TlsProtocol.GetCurrentPrfHash(state.clientContext, handshake.HandshakeHash, null));
            ProcessFinished(handshake.ReceiveMessageBody(HandshakeType.finished), expectedServerVerifyData);

            handshake.Finish();

            if (state.tlsSession != null)
            {
                state.sessionParameters = new SessionParameters.Builder()
                                          .SetCipherSuite(securityParameters.CipherSuite)
                                          .SetCompressionAlgorithm(securityParameters.CompressionAlgorithm)
                                          .SetMasterSecret(securityParameters.MasterSecret)
                                          .SetPeerCertificate(serverCertificate)
                                          .SetPskIdentity(securityParameters.PskIdentity)
                                          .SetSrpIdentity(securityParameters.SrpIdentity)
                                          // TODO Consider filtering extensions that aren't relevant to resumed sessions
                                          .SetServerExtensions(state.serverExtensions)
                                          .Build();

                state.tlsSession = TlsUtilities.ImportSession(state.tlsSession.SessionID, state.sessionParameters);

                state.clientContext.SetResumableSession(state.tlsSession);
            }

            state.client.NotifyHandshakeComplete();

            return(new DtlsTransport(recordLayer));
        }
Ejemplo n.º 26
0
 public override void Close()
 {
     Arrays.fill(_password, ( char )0);
 }
Ejemplo n.º 27
0
 public virtual byte[] GetSigAlgParams()
 {
     return(Arrays.Clone(sigAlgParams));
 }
Ejemplo n.º 28
0
 public override string ToString()
 {
     return("NodeWithPropertyValues{" + "nodeId=" + _nodeId + ", values=" + Arrays.ToString(_values) + '}');
 }
Ejemplo n.º 29
0
 public override int GetHashCode()
 {
     return(Q.GetHashCode() ^ Arrays.GetHashCode(x, 0, 12));
 }
Ejemplo n.º 30
0
        protected override void HandleHandshakeMessage(byte type, MemoryStream buf)
        {
            if (this.mResumedSession)
            {
                if (type != HandshakeType.finished || this.mConnectionState != CS_SERVER_HELLO)
                {
                    throw new TlsFatalAlert(AlertDescription.unexpected_message);
                }

                ProcessFinishedMessage(buf);
                this.mConnectionState = CS_SERVER_FINISHED;

                SendChangeCipherSpecMessage();
                SendFinishedMessage();
                this.mConnectionState = CS_CLIENT_FINISHED;

                CompleteHandshake();
                return;
            }

            switch (type)
            {
            case HandshakeType.certificate:
            {
                switch (this.mConnectionState)
                {
                case CS_SERVER_HELLO:
                case CS_SERVER_SUPPLEMENTAL_DATA:
                {
                    if (this.mConnectionState == CS_SERVER_HELLO)
                    {
                        HandleSupplementalData(null);
                    }

                    // Parse the Certificate message and Send to cipher suite

                    this.mPeerCertificate = Certificate.Parse(buf);

                    AssertEmpty(buf);

                    // TODO[RFC 3546] Check whether empty certificates is possible, allowed, or excludes CertificateStatus
                    if (this.mPeerCertificate == null || this.mPeerCertificate.IsEmpty)
                    {
                        this.mAllowCertificateStatus = false;
                    }

                    this.mKeyExchange.ProcessServerCertificate(this.mPeerCertificate);

                    this.mAuthentication = mTlsClient.GetAuthentication();
                    this.mAuthentication.NotifyServerCertificate(this.mPeerCertificate);

                    break;
                }

                default:
                    throw new TlsFatalAlert(AlertDescription.unexpected_message);
                }

                this.mConnectionState = CS_SERVER_CERTIFICATE;
                break;
            }

            case HandshakeType.certificate_status:
            {
                switch (this.mConnectionState)
                {
                case CS_SERVER_CERTIFICATE:
                {
                    if (!this.mAllowCertificateStatus)
                    {
                        /*
                         * RFC 3546 3.6. If a server returns a "CertificateStatus" message, then the
                         * server MUST have included an extension of type "status_request" with empty
                         * "extension_data" in the extended server hello..
                         */
                        throw new TlsFatalAlert(AlertDescription.unexpected_message);
                    }

                    this.mCertificateStatus = CertificateStatus.Parse(buf);

                    AssertEmpty(buf);

                    // TODO[RFC 3546] Figure out how to provide this to the client/authentication.

                    this.mConnectionState = CS_CERTIFICATE_STATUS;
                    break;
                }

                default:
                    throw new TlsFatalAlert(AlertDescription.unexpected_message);
                }
                break;
            }

            case HandshakeType.finished:
            {
                switch (this.mConnectionState)
                {
                case CS_CLIENT_FINISHED:
                case CS_SERVER_SESSION_TICKET:
                {
                    if (this.mConnectionState == CS_CLIENT_FINISHED && this.mExpectSessionTicket)
                    {
                        /*
                         * RFC 5077 3.3. This message MUST be sent if the server included a
                         * SessionTicket extension in the ServerHello.
                         */
                        throw new TlsFatalAlert(AlertDescription.unexpected_message);
                    }

                    ProcessFinishedMessage(buf);
                    this.mConnectionState = CS_SERVER_FINISHED;

                    CompleteHandshake();
                    break;
                }

                default:
                    throw new TlsFatalAlert(AlertDescription.unexpected_message);
                }
                break;
            }

            case HandshakeType.server_hello:
            {
                switch (this.mConnectionState)
                {
                case CS_CLIENT_HELLO:
                {
                    ReceiveServerHelloMessage(buf);
                    this.mConnectionState = CS_SERVER_HELLO;

                    this.mRecordStream.NotifyHelloComplete();

                    ApplyMaxFragmentLengthExtension();

                    if (this.mResumedSession)
                    {
                        this.mSecurityParameters.masterSecret = Arrays.Clone(this.mSessionParameters.MasterSecret);
                        this.mRecordStream.SetPendingConnectionState(Peer.GetCompression(), Peer.GetCipher());
                    }
                    else
                    {
                        InvalidateSession();

                        if (this.mSelectedSessionID.Length > 0)
                        {
                            this.mTlsSession = new TlsSessionImpl(this.mSelectedSessionID, null);
                        }
                    }

                    break;
                }

                default:
                    throw new TlsFatalAlert(AlertDescription.unexpected_message);
                }
                break;
            }

            case HandshakeType.supplemental_data:
            {
                switch (this.mConnectionState)
                {
                case CS_SERVER_HELLO:
                {
                    HandleSupplementalData(ReadSupplementalDataMessage(buf));
                    break;
                }

                default:
                    throw new TlsFatalAlert(AlertDescription.unexpected_message);
                }
                break;
            }

            case HandshakeType.server_hello_done:
            {
                switch (this.mConnectionState)
                {
                case CS_SERVER_HELLO:
                case CS_SERVER_SUPPLEMENTAL_DATA:
                case CS_SERVER_CERTIFICATE:
                case CS_CERTIFICATE_STATUS:
                case CS_SERVER_KEY_EXCHANGE:
                case CS_CERTIFICATE_REQUEST:
                {
                    if (mConnectionState < CS_SERVER_SUPPLEMENTAL_DATA)
                    {
                        HandleSupplementalData(null);
                    }

                    if (mConnectionState < CS_SERVER_CERTIFICATE)
                    {
                        // There was no server certificate message; check it's OK
                        this.mKeyExchange.SkipServerCredentials();
                        this.mAuthentication = null;
                    }

                    if (mConnectionState < CS_SERVER_KEY_EXCHANGE)
                    {
                        // There was no server key exchange message; check it's OK
                        this.mKeyExchange.SkipServerKeyExchange();
                    }

                    AssertEmpty(buf);

                    this.mConnectionState = CS_SERVER_HELLO_DONE;

                    this.mRecordStream.HandshakeHash.SealHashAlgorithms();

                    IList clientSupplementalData = mTlsClient.GetClientSupplementalData();
                    if (clientSupplementalData != null)
                    {
                        SendSupplementalDataMessage(clientSupplementalData);
                    }
                    this.mConnectionState = CS_CLIENT_SUPPLEMENTAL_DATA;

                    TlsCredentials clientCreds = null;
                    if (mCertificateRequest == null)
                    {
                        this.mKeyExchange.SkipClientCredentials();
                    }
                    else
                    {
                        clientCreds = this.mAuthentication.GetClientCredentials(mCertificateRequest);

                        if (clientCreds == null)
                        {
                            this.mKeyExchange.SkipClientCredentials();

                            /*
                             * RFC 5246 If no suitable certificate is available, the client MUST Send a
                             * certificate message containing no certificates.
                             *
                             * NOTE: In previous RFCs, this was SHOULD instead of MUST.
                             */
                            SendCertificateMessage(Certificate.EmptyChain);
                        }
                        else
                        {
                            this.mKeyExchange.ProcessClientCredentials(clientCreds);

                            SendCertificateMessage(clientCreds.Certificate);
                        }
                    }

                    this.mConnectionState = CS_CLIENT_CERTIFICATE;

                    /*
                     * Send the client key exchange message, depending on the key exchange we are using
                     * in our CipherSuite.
                     */
                    SendClientKeyExchangeMessage();
                    this.mConnectionState = CS_CLIENT_KEY_EXCHANGE;

                    if (TlsUtilities.IsSsl(Context))
                    {
                        EstablishMasterSecret(Context, mKeyExchange);
                    }

                    TlsHandshakeHash prepareFinishHash = mRecordStream.PrepareToFinish();
                    this.mSecurityParameters.sessionHash = GetCurrentPrfHash(Context, prepareFinishHash, null);

                    if (!TlsUtilities.IsSsl(Context))
                    {
                        EstablishMasterSecret(Context, mKeyExchange);
                    }

                    mRecordStream.SetPendingConnectionState(Peer.GetCompression(), Peer.GetCipher());

                    if (clientCreds != null && clientCreds is TlsSignerCredentials)
                    {
                        TlsSignerCredentials signerCredentials = (TlsSignerCredentials)clientCreds;

                        /*
                         * RFC 5246 4.7. digitally-signed element needs SignatureAndHashAlgorithm from TLS 1.2
                         */
                        SignatureAndHashAlgorithm signatureAndHashAlgorithm = TlsUtilities.GetSignatureAndHashAlgorithm(
                            Context, signerCredentials);

                        byte[] hash;
                        if (signatureAndHashAlgorithm == null)
                        {
                            hash = mSecurityParameters.SessionHash;
                        }
                        else
                        {
                            hash = prepareFinishHash.GetFinalHash(signatureAndHashAlgorithm.Hash);
                        }

                        byte[]          signature         = signerCredentials.GenerateCertificateSignature(hash);
                        DigitallySigned certificateVerify = new DigitallySigned(signatureAndHashAlgorithm, signature);
                        SendCertificateVerifyMessage(certificateVerify);

                        this.mConnectionState = CS_CERTIFICATE_VERIFY;
                    }

                    SendChangeCipherSpecMessage();
                    SendFinishedMessage();
                    break;
                }

                default:
                    throw new TlsFatalAlert(AlertDescription.unexpected_message);
                }

                this.mConnectionState = CS_CLIENT_FINISHED;
                break;
            }

            case HandshakeType.server_key_exchange:
            {
                switch (this.mConnectionState)
                {
                case CS_SERVER_HELLO:
                case CS_SERVER_SUPPLEMENTAL_DATA:
                case CS_SERVER_CERTIFICATE:
                case CS_CERTIFICATE_STATUS:
                {
                    if (mConnectionState < CS_SERVER_SUPPLEMENTAL_DATA)
                    {
                        HandleSupplementalData(null);
                    }

                    if (mConnectionState < CS_SERVER_CERTIFICATE)
                    {
                        // There was no server certificate message; check it's OK
                        this.mKeyExchange.SkipServerCredentials();
                        this.mAuthentication = null;
                    }

                    this.mKeyExchange.ProcessServerKeyExchange(buf);

                    AssertEmpty(buf);
                    break;
                }

                default:
                    throw new TlsFatalAlert(AlertDescription.unexpected_message);
                }

                this.mConnectionState = CS_SERVER_KEY_EXCHANGE;
                break;
            }

            case HandshakeType.certificate_request:
            {
                switch (this.mConnectionState)
                {
                case CS_SERVER_CERTIFICATE:
                case CS_CERTIFICATE_STATUS:
                case CS_SERVER_KEY_EXCHANGE:
                {
                    if (this.mConnectionState != CS_SERVER_KEY_EXCHANGE)
                    {
                        // There was no server key exchange message; check it's OK
                        this.mKeyExchange.SkipServerKeyExchange();
                    }

                    if (this.mAuthentication == null)
                    {
                        /*
                         * RFC 2246 7.4.4. It is a fatal handshake_failure alert for an anonymous server
                         * to request client identification.
                         */
                        throw new TlsFatalAlert(AlertDescription.handshake_failure);
                    }

                    this.mCertificateRequest = CertificateRequest.Parse(Context, buf);

                    AssertEmpty(buf);

                    this.mKeyExchange.ValidateCertificateRequest(this.mCertificateRequest);

                    /*
                     * TODO Give the client a chance to immediately select the CertificateVerify hash
                     * algorithm here to avoid tracking the other hash algorithms unnecessarily?
                     */
                    TlsUtilities.TrackHashAlgorithms(this.mRecordStream.HandshakeHash,
                                                     this.mCertificateRequest.SupportedSignatureAlgorithms);

                    break;
                }

                default:
                    throw new TlsFatalAlert(AlertDescription.unexpected_message);
                }

                this.mConnectionState = CS_CERTIFICATE_REQUEST;
                break;
            }

            case HandshakeType.session_ticket:
            {
                switch (this.mConnectionState)
                {
                case CS_CLIENT_FINISHED:
                {
                    if (!this.mExpectSessionTicket)
                    {
                        /*
                         * RFC 5077 3.3. This message MUST NOT be sent if the server did not include a
                         * SessionTicket extension in the ServerHello.
                         */
                        throw new TlsFatalAlert(AlertDescription.unexpected_message);
                    }

                    /*
                     * RFC 5077 3.4. If the client receives a session ticket from the server, then it
                     * discards any Session ID that was sent in the ServerHello.
                     */
                    InvalidateSession();

                    ReceiveNewSessionTicketMessage(buf);
                    break;
                }

                default:
                    throw new TlsFatalAlert(AlertDescription.unexpected_message);
                }

                this.mConnectionState = CS_SERVER_SESSION_TICKET;
                break;
            }

            case HandshakeType.hello_request:
            {
                AssertEmpty(buf);

                /*
                 * RFC 2246 7.4.1.1 Hello request This message will be ignored by the client if the
                 * client is currently negotiating a session. This message may be ignored by the client
                 * if it does not wish to renegotiate a session, or the client may, if it wishes,
                 * respond with a no_renegotiation alert.
                 */
                if (this.mConnectionState == CS_END)
                {
                    RefuseRenegotiation();
                }
                break;
            }

            case HandshakeType.client_hello:
            case HandshakeType.client_key_exchange:
            case HandshakeType.certificate_verify:
            case HandshakeType.hello_verify_request:
            default:
                throw new TlsFatalAlert(AlertDescription.unexpected_message);
            }
        }
Ejemplo n.º 31
0
        private List<ReflectionClass> ParseRecord(List<ReflectionClass> reflectionClass)
        {
            List<ReflectionClass> returnReflectionClass = new List<ReflectionClass>();
            string[] splitedString;
            List<Arrays> arrayNames = new List<Arrays>();
            Arrays oneList;

            foreach (ReflectionClass r in reflectionClass)
            {
                splitedString = r.name.Split(new char[] { '.' });
                for (int i = 0; i < splitedString.Length; i++)
                {
                    if (splitedString[i].Contains('[') && splitedString[i].Contains(']'))
                    {
                        string arrayFullName = "";
                        oneList = new Arrays();
                        string[] splitNameNumber = splitedString[i].Split((new char[] { '[', ']' }), StringSplitOptions.RemoveEmptyEntries);

                        for (int j = 0; j < r.paramStructure.Count; j++)
                        {
                            arrayFullName += r.paramStructure[j] + ".";
                        }
                        arrayFullName += splitNameNumber[0];

                        oneList.arrayName = arrayFullName;
                        oneList.maxCount = Convert.ToInt32(splitNameNumber[1]);

                        int result = arrayNames.FindIndex(
                            delegate(Arrays arrayName)
                            {
                                if (arrayName.arrayName.Equals(arrayFullName))
                                    return true;
                                return false;
                            }
                        );

                        if (result != -1)
                        {
                            if (arrayNames[result].maxCount < oneList.maxCount)
                            {
                                Arrays temp = new Arrays();
                                temp.arrayName = oneList.arrayName;
                                temp.maxCount = oneList.maxCount;
                                arrayNames[result] = temp;
                            }
                        }
                        else
                        {
                            arrayNames.Add(oneList);
                        }
                    }
                    r.paramStructure.Add(splitedString[i]);
                }
                returnReflectionClass.Add(r);
            }
            foreach (Arrays n in arrayNames)
            {
                ReflectionClass r = new ReflectionClass();
                r.name = n.arrayName + ".arrayCount";
                r.value = (n.maxCount + 1).ToString();
                returnReflectionClass.Add(r);
            }
            return returnReflectionClass;
        }
Ejemplo n.º 32
0
        protected virtual void SendClientHelloMessage()
        {
            this.mRecordStream.SetWriteVersion(this.mTlsClient.ClientHelloRecordLayerVersion);

            ProtocolVersion client_version = this.mTlsClient.ClientVersion;

            if (client_version.IsDtls)
            {
                throw new TlsFatalAlert(AlertDescription.internal_error);
            }

            ContextAdmin.SetClientVersion(client_version);

            /*
             * TODO RFC 5077 3.4. When presenting a ticket, the client MAY generate and include a
             * Session ID in the TLS ClientHello.
             */
            byte[] session_id = TlsUtilities.EmptyBytes;
            if (this.mTlsSession != null)
            {
                session_id = this.mTlsSession.SessionID;
                if (session_id == null || session_id.Length > 32)
                {
                    session_id = TlsUtilities.EmptyBytes;
                }
            }

            bool fallback = this.mTlsClient.IsFallback;

            this.mOfferedCipherSuites = this.mTlsClient.GetCipherSuites();

            this.mOfferedCompressionMethods = this.mTlsClient.GetCompressionMethods();

            if (session_id.Length > 0 && this.mSessionParameters != null)
            {
                if (!Arrays.Contains(this.mOfferedCipherSuites, mSessionParameters.CipherSuite) ||
                    !Arrays.Contains(this.mOfferedCompressionMethods, mSessionParameters.CompressionAlgorithm))
                {
                    session_id = TlsUtilities.EmptyBytes;
                }
            }

            this.mClientExtensions = this.mTlsClient.GetClientExtensions();

            HandshakeMessage message = new HandshakeMessage(HandshakeType.client_hello);

            TlsUtilities.WriteVersion(client_version, message);

            message.Write(this.mSecurityParameters.ClientRandom);

            TlsUtilities.WriteOpaque8(session_id, message);

            // Cipher Suites (and SCSV)
            {
                /*
                 * RFC 5746 3.4. The client MUST include either an empty "renegotiation_info" extension,
                 * or the TLS_EMPTY_RENEGOTIATION_INFO_SCSV signaling cipher suite value in the
                 * ClientHello. Including both is NOT RECOMMENDED.
                 */
                byte[] renegExtData = TlsUtilities.GetExtensionData(mClientExtensions, ExtensionType.renegotiation_info);
                bool   noRenegExt   = (null == renegExtData);

                bool noRenegScsv = !Arrays.Contains(mOfferedCipherSuites, CipherSuite.TLS_EMPTY_RENEGOTIATION_INFO_SCSV);

                if (noRenegExt && noRenegScsv)
                {
                    // TODO Consider whether to default to a client extension instead
                    //                this.mClientExtensions = TlsExtensionsUtilities.EnsureExtensionsInitialised(this.mClientExtensions);
                    //                this.mClientExtensions[ExtensionType.renegotiation_info] = CreateRenegotiationInfo(TlsUtilities.EmptyBytes);
                    this.mOfferedCipherSuites = Arrays.Append(mOfferedCipherSuites, CipherSuite.TLS_EMPTY_RENEGOTIATION_INFO_SCSV);
                }

                /*
                 * RFC 7507 4. If a client sends a ClientHello.client_version containing a lower value
                 * than the latest (highest-valued) version supported by the client, it SHOULD include
                 * the TLS_FALLBACK_SCSV cipher suite value in ClientHello.cipher_suites [..]. (The
                 * client SHOULD put TLS_FALLBACK_SCSV after all cipher suites that it actually intends
                 * to negotiate.)
                 */
                if (fallback && !Arrays.Contains(mOfferedCipherSuites, CipherSuite.TLS_FALLBACK_SCSV))
                {
                    this.mOfferedCipherSuites = Arrays.Append(mOfferedCipherSuites, CipherSuite.TLS_FALLBACK_SCSV);
                }

                TlsUtilities.WriteUint16ArrayWithUint16Length(mOfferedCipherSuites, message);
            }

            TlsUtilities.WriteUint8ArrayWithUint8Length(mOfferedCompressionMethods, message);

            if (mClientExtensions != null)
            {
                WriteExtensions(message, mClientExtensions);
            }

            message.WriteToRecordStream(this);
        }
Ejemplo n.º 33
0
 private static CharArraySet makeDictionary(params string[] dictionary)
 {
     return(new CharArraySet(TEST_VERSION_CURRENT, Arrays.AsList(dictionary), true));
 }
Ejemplo n.º 34
0
        public virtual void TestClassicCounterHistoricalMain()
        {
            c.SetCount("p", 0);
            c.SetCount("q", 2);
            ClassicCounter <string> small_c = new ClassicCounter <string>(c);
            ICounter <string>       c7      = c.GetFactory().Create();

            c7.AddAll(c);
            NUnit.Framework.Assert.AreEqual(c.TotalCount(), 2.0);
            c.IncrementCount("p");
            NUnit.Framework.Assert.AreEqual(c.TotalCount(), 3.0);
            c.IncrementCount("p", 2.0);
            NUnit.Framework.Assert.AreEqual(Counters.Min(c), 2.0);
            NUnit.Framework.Assert.AreEqual(Counters.Argmin(c), "q");
            // Now p is p=3.0, q=2.0
            c.SetCount("w", -5.0);
            c.SetCount("x", -4.5);
            IList <string> biggestKeys = new List <string>(c.KeySet());

            NUnit.Framework.Assert.AreEqual(biggestKeys.Count, 4);
            biggestKeys.Sort(Counters.ToComparator(c, false, true));
            NUnit.Framework.Assert.AreEqual("w", biggestKeys[0]);
            NUnit.Framework.Assert.AreEqual("x", biggestKeys[1]);
            NUnit.Framework.Assert.AreEqual("p", biggestKeys[2]);
            NUnit.Framework.Assert.AreEqual("q", biggestKeys[3]);
            NUnit.Framework.Assert.AreEqual(Counters.Min(c), -5.0, Tolerance);
            NUnit.Framework.Assert.AreEqual(Counters.Argmin(c), "w");
            NUnit.Framework.Assert.AreEqual(Counters.Max(c), 3.0, Tolerance);
            NUnit.Framework.Assert.AreEqual(Counters.Argmax(c), "p");
            if (integral)
            {
                NUnit.Framework.Assert.AreEqual(Counters.Mean(c), -1.0);
            }
            else
            {
                NUnit.Framework.Assert.AreEqual(Counters.Mean(c), -1.125, Tolerance);
            }
            if (!integral)
            {
                // only do this for floating point counters.  Too much bother to rewrite
                c.SetCount("x", -2.5);
                ClassicCounter <string> c2 = new ClassicCounter <string>(c);
                NUnit.Framework.Assert.AreEqual(3.0, c2.GetCount("p"));
                NUnit.Framework.Assert.AreEqual(2.0, c2.GetCount("q"));
                NUnit.Framework.Assert.AreEqual(-5.0, c2.GetCount("w"));
                NUnit.Framework.Assert.AreEqual(-2.5, c2.GetCount("x"));
                ICounter <string> c3 = c.GetFactory().Create();
                foreach (string str in c2.KeySet())
                {
                    c3.IncrementCount(str);
                }
                NUnit.Framework.Assert.AreEqual(1.0, c3.GetCount("p"));
                NUnit.Framework.Assert.AreEqual(1.0, c3.GetCount("q"));
                NUnit.Framework.Assert.AreEqual(1.0, c3.GetCount("w"));
                NUnit.Framework.Assert.AreEqual(1.0, c3.GetCount("x"));
                Counters.AddInPlace(c2, c3, 10.0);
                NUnit.Framework.Assert.AreEqual(13.0, c2.GetCount("p"));
                NUnit.Framework.Assert.AreEqual(12.0, c2.GetCount("q"));
                NUnit.Framework.Assert.AreEqual(5.0, c2.GetCount("w"));
                NUnit.Framework.Assert.AreEqual(7.5, c2.GetCount("x"));
                c3.AddAll(c);
                NUnit.Framework.Assert.AreEqual(4.0, c3.GetCount("p"));
                NUnit.Framework.Assert.AreEqual(3.0, c3.GetCount("q"));
                NUnit.Framework.Assert.AreEqual(-4.0, c3.GetCount("w"));
                NUnit.Framework.Assert.AreEqual(-1.5, c3.GetCount("x"));
                Counters.SubtractInPlace(c3, c);
                NUnit.Framework.Assert.AreEqual(1.0, c3.GetCount("p"));
                NUnit.Framework.Assert.AreEqual(1.0, c3.GetCount("q"));
                NUnit.Framework.Assert.AreEqual(1.0, c3.GetCount("w"));
                NUnit.Framework.Assert.AreEqual(1.0, c3.GetCount("x"));
                foreach (string str_1 in c.KeySet())
                {
                    c3.IncrementCount(str_1);
                }
                NUnit.Framework.Assert.AreEqual(2.0, c3.GetCount("p"));
                NUnit.Framework.Assert.AreEqual(2.0, c3.GetCount("q"));
                NUnit.Framework.Assert.AreEqual(2.0, c3.GetCount("w"));
                NUnit.Framework.Assert.AreEqual(2.0, c3.GetCount("x"));
                Counters.DivideInPlace(c2, c3);
                NUnit.Framework.Assert.AreEqual(6.5, c2.GetCount("p"));
                NUnit.Framework.Assert.AreEqual(6.0, c2.GetCount("q"));
                NUnit.Framework.Assert.AreEqual(2.5, c2.GetCount("w"));
                NUnit.Framework.Assert.AreEqual(3.75, c2.GetCount("x"));
                Counters.DivideInPlace(c2, 0.5);
                NUnit.Framework.Assert.AreEqual(13.0, c2.GetCount("p"));
                NUnit.Framework.Assert.AreEqual(12.0, c2.GetCount("q"));
                NUnit.Framework.Assert.AreEqual(5.0, c2.GetCount("w"));
                NUnit.Framework.Assert.AreEqual(7.5, c2.GetCount("x"));
                Counters.MultiplyInPlace(c2, 2.0);
                NUnit.Framework.Assert.AreEqual(26.0, c2.GetCount("p"));
                NUnit.Framework.Assert.AreEqual(24.0, c2.GetCount("q"));
                NUnit.Framework.Assert.AreEqual(10.0, c2.GetCount("w"));
                NUnit.Framework.Assert.AreEqual(15.0, c2.GetCount("x"));
                Counters.DivideInPlace(c2, 2.0);
                NUnit.Framework.Assert.AreEqual(13.0, c2.GetCount("p"));
                NUnit.Framework.Assert.AreEqual(12.0, c2.GetCount("q"));
                NUnit.Framework.Assert.AreEqual(5.0, c2.GetCount("w"));
                NUnit.Framework.Assert.AreEqual(7.5, c2.GetCount("x"));
                foreach (string str_2 in c2.KeySet())
                {
                    c2.IncrementCount(str_2);
                }
                NUnit.Framework.Assert.AreEqual(14.0, c2.GetCount("p"));
                NUnit.Framework.Assert.AreEqual(13.0, c2.GetCount("q"));
                NUnit.Framework.Assert.AreEqual(6.0, c2.GetCount("w"));
                NUnit.Framework.Assert.AreEqual(8.5, c2.GetCount("x"));
                foreach (string str_3 in c.KeySet())
                {
                    c2.IncrementCount(str_3);
                }
                NUnit.Framework.Assert.AreEqual(15.0, c2.GetCount("p"));
                NUnit.Framework.Assert.AreEqual(14.0, c2.GetCount("q"));
                NUnit.Framework.Assert.AreEqual(7.0, c2.GetCount("w"));
                NUnit.Framework.Assert.AreEqual(9.5, c2.GetCount("x"));
                c2.AddAll(small_c);
                NUnit.Framework.Assert.AreEqual(15.0, c2.GetCount("p"));
                NUnit.Framework.Assert.AreEqual(16.0, c2.GetCount("q"));
                NUnit.Framework.Assert.AreEqual(7.0, c2.GetCount("w"));
                NUnit.Framework.Assert.AreEqual(9.5, c2.GetCount("x"));
                NUnit.Framework.Assert.AreEqual(new HashSet <string>(Arrays.AsList("p", "q")), Counters.KeysAbove(c2, 14));
                NUnit.Framework.Assert.AreEqual(new HashSet <string>(Arrays.AsList("q")), Counters.KeysAt(c2, 16));
                NUnit.Framework.Assert.AreEqual(new HashSet <string>(Arrays.AsList("x", "w")), Counters.KeysBelow(c2, 9.5));
                Counters.AddInPlace(c2, small_c, -6);
                NUnit.Framework.Assert.AreEqual(15.0, c2.GetCount("p"));
                NUnit.Framework.Assert.AreEqual(4.0, c2.GetCount("q"));
                NUnit.Framework.Assert.AreEqual(7.0, c2.GetCount("w"));
                NUnit.Framework.Assert.AreEqual(9.5, c2.GetCount("x"));
                Counters.SubtractInPlace(c2, small_c);
                Counters.SubtractInPlace(c2, small_c);
                Counters.RetainNonZeros(c2);
                NUnit.Framework.Assert.AreEqual(15.0, c2.GetCount("p"));
                NUnit.Framework.Assert.IsFalse(c2.ContainsKey("q"));
                NUnit.Framework.Assert.AreEqual(7.0, c2.GetCount("w"));
                NUnit.Framework.Assert.AreEqual(9.5, c2.GetCount("x"));
            }
            // serialize to Stream
            if (c is ISerializable)
            {
                try
                {
                    ByteArrayOutputStream baos = new ByteArrayOutputStream();
                    ObjectOutputStream    @out = new ObjectOutputStream(new BufferedOutputStream(baos));
                    @out.WriteObject(c);
                    @out.Close();
                    // reconstitute
                    byte[]            bytes = baos.ToByteArray();
                    ObjectInputStream @in   = new ObjectInputStream(new BufferedInputStream(new ByteArrayInputStream(bytes)));
                    c = IOUtils.ReadObjectFromObjectStream(@in);
                    @in.Close();
                    if (!this.integral)
                    {
                        NUnit.Framework.Assert.AreEqual(-2.5, c.TotalCount());
                        NUnit.Framework.Assert.AreEqual(-5.0, Counters.Min(c));
                        NUnit.Framework.Assert.AreEqual("w", Counters.Argmin(c));
                    }
                    c.Clear();
                    if (!this.integral)
                    {
                        NUnit.Framework.Assert.AreEqual(0.0, c.TotalCount());
                    }
                }
                catch (IOException ioe)
                {
                    Fail("IOException: " + ioe);
                }
                catch (TypeLoadException cce)
                {
                    Fail("ClassNotFoundException: " + cce);
                }
            }
        }