示例#1
0
    public virtual void Encode(Stream output)
    {
        if (mCertificateTypes == null || mCertificateTypes.Length == 0)
        {
            TlsUtilities.WriteUint8(0, output);
        }
        else
        {
            TlsUtilities.WriteUint8ArrayWithUint8Length(mCertificateTypes, output);
        }
        if (mSupportedSignatureAlgorithms != null)
        {
            TlsUtilities.EncodeSupportedSignatureAlgorithms(mSupportedSignatureAlgorithms, allowAnonymous: false, output);
        }
        if (mCertificateAuthorities == null || mCertificateAuthorities.Count < 1)
        {
            TlsUtilities.WriteUint16(0, output);
            return;
        }
        IList list = Platform.CreateArrayList(mCertificateAuthorities.Count);
        int   num  = 0;

        foreach (Asn1Encodable mCertificateAuthority in mCertificateAuthorities)
        {
            byte[] encoded = mCertificateAuthority.GetEncoded("DER");
            list.Add(encoded);
            num += encoded.Length + 2;
        }
        TlsUtilities.CheckUint16(num);
        TlsUtilities.WriteUint16(num, output);
        foreach (byte[] item in list)
        {
            TlsUtilities.WriteOpaque16(item, output);
        }
    }
 public virtual void Encode(Stream output)
 {
     if (mResponderIDList == null || mResponderIDList.Count < 1)
     {
         TlsUtilities.WriteUint16(0, output);
     }
     else
     {
         MemoryStream memoryStream = new MemoryStream();
         for (int i = 0; i < mResponderIDList.Count; i++)
         {
             ResponderID responderID = (ResponderID)mResponderIDList[i];
             byte[]      encoded     = responderID.GetEncoded("DER");
             TlsUtilities.WriteOpaque16(encoded, memoryStream);
         }
         TlsUtilities.CheckUint16(memoryStream.Length);
         TlsUtilities.WriteUint16((int)memoryStream.Length, output);
         memoryStream.WriteTo(output);
     }
     if (mRequestExtensions == null)
     {
         TlsUtilities.WriteUint16(0, output);
         return;
     }
     byte[] encoded2 = mRequestExtensions.GetEncoded("DER");
     TlsUtilities.CheckUint16(encoded2.Length);
     TlsUtilities.WriteUint16(encoded2.Length, output);
     output.Write(encoded2, 0, encoded2.Length);
 }
示例#3
0
        /**
         * Encode this {@link OcspStatusRequest} to a {@link Stream}.
         *
         * @param output
         *            the {@link Stream} to encode to.
         * @throws IOException
         */
        public virtual void Encode(Stream output)
        {
            if (mResponderIDList == null || mResponderIDList.Count < 1)
            {
                TlsUtilities.WriteUint16(0, output);
            }
            else
            {
                MemoryStream buf = new MemoryStream();
                for (int i = 0; i < mResponderIDList.Count; ++i)
                {
                    ResponderID responderID = (ResponderID)mResponderIDList[i];
                    byte[]      derEncoding = responderID.GetEncoded(Asn1Encodable.Der);
                    TlsUtilities.WriteOpaque16(derEncoding, buf);
                }
                TlsUtilities.CheckUint16(buf.Length);
                TlsUtilities.WriteUint16((int)buf.Length, output);
                buf.WriteTo(output);
            }

            if (mRequestExtensions == null)
            {
                TlsUtilities.WriteUint16(0, output);
            }
            else
            {
                byte[] derEncoding = mRequestExtensions.GetEncoded(Asn1Encodable.Der);
                TlsUtilities.CheckUint16(derEncoding.Length);
                TlsUtilities.WriteUint16(derEncoding.Length, output);
                output.Write(derEncoding, 0, derEncoding.Length);
            }
        }
示例#4
0
 protected virtual byte[] GetAdditionalData(long seqNo, byte type, int len)
 {
     byte[] array = new byte[13];
     TlsUtilities.WriteUint64(seqNo, array, 0);
     TlsUtilities.WriteUint8(type, array, 8);
     TlsUtilities.WriteVersion(context.ServerVersion, array, 9);
     TlsUtilities.WriteUint16(len, array, 11);
     return(array);
 }
示例#5
0
        internal void EncodeTo(Stream output)
        {
            long num = Length - 2;

            TlsUtilities.CheckUint16(num);
            Position = 0L;
            TlsUtilities.WriteUint16((int)num, this);
            WriteTo(output);
            Platform.Dispose(this);
        }
 public virtual void Encode(TlsContext context, Stream output)
 {
     TlsUtilities.WriteUint8(mType, output);
     TlsUtilities.CheckUint16(mPayload.Length);
     TlsUtilities.WriteUint16(mPayload.Length, output);
     output.Write(mPayload, 0, mPayload.Length);
     byte[] array = new byte[mPaddingLength];
     context.NonceRandomGenerator.NextBytes(array);
     output.Write(array, 0, array.Length);
 }
 public static void WriteNamedECParameters(int namedCurve, Stream output)
 {
     if (!NamedCurve.RefersToASpecificNamedCurve(namedCurve))
     {
         throw new TlsFatalAlert(80);
     }
     TlsUtilities.WriteUint8(3, output);
     TlsUtilities.CheckUint16(namedCurve);
     TlsUtilities.WriteUint16(namedCurve, output);
 }
示例#8
0
            internal void EncodeTo(Stream output)
            {
                // Patch actual length back in
                long length = Length - 2;

                TlsUtilities.CheckUint16(length);
                this.Position = 0;
                TlsUtilities.WriteUint16((int)length, this);
                Streams.WriteBufTo(this, output);
                Platform.Dispose(this);
            }
示例#9
0
            internal void EncodeTo(Stream output)
            {
                // Patch actual length back in
                long length = Length - 2;

                TlsUtilities.CheckUint16(length);
                this.Position = 0;
                TlsUtilities.WriteUint16((int)length, this);
                Streams.WriteBufTo(this, output);
                BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Platform.Dispose(this);
            }
    private void WriteHandshakeFragment(Message message, int fragment_offset, int fragment_length)
    {
        RecordLayerBuffer recordLayerBuffer = new RecordLayerBuffer(12 + fragment_length);

        TlsUtilities.WriteUint8(message.Type, recordLayerBuffer);
        TlsUtilities.WriteUint24(message.Body.Length, recordLayerBuffer);
        TlsUtilities.WriteUint16(message.Seq, recordLayerBuffer);
        TlsUtilities.WriteUint24(fragment_offset, recordLayerBuffer);
        TlsUtilities.WriteUint24(fragment_length, recordLayerBuffer);
        recordLayerBuffer.Write(message.Body, fragment_offset, fragment_length);
        recordLayerBuffer.SendToRecordLayer(mRecordLayer);
    }
示例#11
0
        /**
         * Encode this {@link ServerNameList} to a {@link Stream}.
         *
         * @param output
         *            the {@link Stream} to encode to.
         * @throws IOException
         */
        public virtual void Encode(Stream output)
        {
            MemoryStream buf = new MemoryStream();

            foreach (ServerName entry in ServerNames)
            {
                entry.Encode(buf);
            }

            TlsUtilities.CheckUint16(buf.Length);
            TlsUtilities.WriteUint16((int)buf.Length, output);
            buf.WriteTo(output);
        }
示例#12
0
        private void WriteHandshakeFragment(Message message, int fragment_offset, int fragment_length)
        {
            RecordLayerBuffer fragment = new RecordLayerBuffer(MessageHeaderLength + fragment_length);

            TlsUtilities.WriteUint8(message.Type, fragment);
            TlsUtilities.WriteUint24(message.Body.Length, fragment);
            TlsUtilities.WriteUint16(message.Seq, fragment);
            TlsUtilities.WriteUint24(fragment_offset, fragment);
            TlsUtilities.WriteUint24(fragment_length, fragment);
            fragment.Write(message.Body, fragment_offset, fragment_length);

            fragment.SendToRecordLayer(mRecordLayer);
        }
        public virtual byte[] ExportKeyingMaterial(string asciiLabel, byte[] context_value, int length)
        {
            if (context_value != null && !TlsUtilities.IsValidUint16(context_value.Length))
            {
                throw new ArgumentException("must have length less than 2^16 (or be null)", "context_value");
            }

            SecurityParameters sp = SecurityParameters;

            if (!sp.IsExtendedMasterSecret)
            {
                /*
                 * RFC 7627 5.4. If a client or server chooses to continue with a full handshake without
                 * the extended master secret extension, [..] the client or server MUST NOT export any
                 * key material based on the new master secret for any subsequent application-level
                 * authentication. In particular, it MUST disable [RFC5705] [..].
                 */
                throw new InvalidOperationException("cannot export keying material without extended_master_secret");
            }

            byte[] cr = sp.ClientRandom, sr = sp.ServerRandom;

            int seedLength = cr.Length + sr.Length;

            if (context_value != null)
            {
                seedLength += (2 + context_value.Length);
            }

            byte[] seed    = new byte[seedLength];
            int    seedPos = 0;

            Array.Copy(cr, 0, seed, seedPos, cr.Length);
            seedPos += cr.Length;
            Array.Copy(sr, 0, seed, seedPos, sr.Length);
            seedPos += sr.Length;
            if (context_value != null)
            {
                TlsUtilities.WriteUint16(context_value.Length, seed, seedPos);
                seedPos += 2;
                Array.Copy(context_value, 0, seed, seedPos, context_value.Length);
                seedPos += context_value.Length;
            }

            if (seedPos != seedLength)
            {
                throw new InvalidOperationException("error in calculation of seed for export");
            }

            return(TlsUtilities.PRF(this, sp.MasterSecret, asciiLabel, seed, length));
        }
示例#14
0
        public static void WriteExplicitECParameters(byte[] ecPointFormats, ECDomainParameters ecParameters,
                                                     Stream output)
        {
            ECCurve curve = ecParameters.Curve;

            if (ECAlgorithms.IsFpCurve(curve))
            {
                TlsUtilities.WriteUint8(ECCurveType.explicit_prime, output);

                WriteECParameter(curve.Field.Characteristic, output);
            }
            else if (ECAlgorithms.IsF2mCurve(curve))
            {
                IPolynomialExtensionField field = (IPolynomialExtensionField)curve.Field;
                int[] exponents = field.MinimalPolynomial.GetExponentsPresent();

                TlsUtilities.WriteUint8(ECCurveType.explicit_char2, output);

                int m = exponents[exponents.Length - 1];
                TlsUtilities.CheckUint16(m);
                TlsUtilities.WriteUint16(m, output);

                if (exponents.Length == 3)
                {
                    TlsUtilities.WriteUint8(ECBasisType.ec_basis_trinomial, output);
                    WriteECExponent(exponents[1], output);
                }
                else if (exponents.Length == 5)
                {
                    TlsUtilities.WriteUint8(ECBasisType.ec_basis_pentanomial, output);
                    WriteECExponent(exponents[1], output);
                    WriteECExponent(exponents[2], output);
                    WriteECExponent(exponents[3], output);
                }
                else
                {
                    throw new ArgumentException("Only trinomial and pentomial curves are supported");
                }
            }
            else
            {
                throw new ArgumentException("'ecParameters' not a known curve type");
            }

            WriteECFieldElement(curve.A, output);
            WriteECFieldElement(curve.B, output);
            TlsUtilities.WriteOpaque8(SerializeECPoint(ecPointFormats, ecParameters.G), output);
            WriteECParameter(ecParameters.N, output);
            WriteECParameter(ecParameters.H, output);
        }
示例#15
0
    protected internal static void WriteSupplementalData(Stream output, IList supplementalData)
    {
        MemoryStream memoryStream = new MemoryStream();

        foreach (SupplementalDataEntry supplementalDatum in supplementalData)
        {
            int dataType = supplementalDatum.DataType;
            TlsUtilities.CheckUint16(dataType);
            TlsUtilities.WriteUint16(dataType, memoryStream);
            TlsUtilities.WriteOpaque16(supplementalDatum.Data, memoryStream);
        }
        byte[] buf = memoryStream.ToArray();
        TlsUtilities.WriteOpaque24(buf, output);
    }
示例#16
0
        /// <exception cref="IOException"></exception>
        protected /*virtual */ BufferSegment GetAdditionalData(long seqNo, byte type, int len)
        {
            /*
             * additional_data = seq_num + TLSCompressed.type + TLSCompressed.version +
             * TLSCompressed.length
             */
            byte[] additional_data = BufferPool.Get(13, true);
            TlsUtilities.WriteUint64(seqNo, additional_data, 0);
            TlsUtilities.WriteUint8(type, additional_data, 8);
            TlsUtilities.WriteVersion(context.ServerVersion, additional_data, 9);
            TlsUtilities.WriteUint16(len, additional_data, 11);

            return(new BufferSegment(additional_data, 0, 13));
        }
示例#17
0
        /// <exception cref="IOException"></exception>
        protected virtual byte[] GetAdditionalData(long seqNo, byte type, int len)
        {
            /*
             * additional_data = seq_num + TLSCompressed.type + TLSCompressed.version +
             * TLSCompressed.length
             */
            byte[] additional_data = new byte[13];
            TlsUtilities.WriteUint64(seqNo, additional_data, 0);
            TlsUtilities.WriteUint8(type, additional_data, 8);
            TlsUtilities.WriteVersion(context.ServerVersion, additional_data, 9);
            TlsUtilities.WriteUint16(len, additional_data, 11);

            return(additional_data);
        }
示例#18
0
    protected internal static void WriteExtensions(Stream output, IDictionary extensions)
    {
        MemoryStream memoryStream = new MemoryStream();

        foreach (object key in extensions.Keys)
        {
            int    num = (int)key;
            byte[] buf = (byte[])extensions[num];
            TlsUtilities.CheckUint16(num);
            TlsUtilities.WriteUint16(num, memoryStream);
            TlsUtilities.WriteOpaque16(buf, memoryStream);
        }
        byte[] buf2 = memoryStream.ToArray();
        TlsUtilities.WriteOpaque16(buf2, output);
    }
示例#19
0
        public static void WriteNamedECParameters(int namedCurve, Stream output)
        {
            if (!NamedCurve.RefersToASpecificNamedCurve(namedCurve))
            {
                /*
                 * RFC 4492 5.4. All those values of NamedCurve are allowed that refer to a specific
                 * curve. Values of NamedCurve that indicate support for a class of explicitly defined
                 * curves are not allowed here [...].
                 */
                throw new TlsFatalAlert(AlertDescription.internal_error);
            }

            TlsUtilities.WriteUint8(ECCurveType.named_curve, output);
            TlsUtilities.CheckUint16(namedCurve);
            TlsUtilities.WriteUint16(namedCurve, output);
        }
 private Message UpdateHandshakeMessagesDigest(Message message)
 {
     if (message.Type != 0)
     {
         byte[] body  = message.Body;
         byte[] array = new byte[12];
         TlsUtilities.WriteUint8(message.Type, array, 0);
         TlsUtilities.WriteUint24(body.Length, array, 1);
         TlsUtilities.WriteUint16(message.Seq, array, 4);
         TlsUtilities.WriteUint24(0, array, 6);
         TlsUtilities.WriteUint24(body.Length, array, 9);
         mHandshakeHash.BlockUpdate(array, 0, array.Length);
         mHandshakeHash.BlockUpdate(body, 0, body.Length);
     }
     return(message);
 }
示例#21
0
 private Message UpdateHandshakeMessagesDigest(Message message)
 {
     if (message.Type != HandshakeType.hello_request)
     {
         byte[] body = message.Body;
         byte[] buf  = new byte[MessageHeaderLength];
         TlsUtilities.WriteUint8(message.Type, buf, 0);
         TlsUtilities.WriteUint24(body.Length, buf, 1);
         TlsUtilities.WriteUint16(message.Seq, buf, 4);
         TlsUtilities.WriteUint24(0, buf, 6);
         TlsUtilities.WriteUint24(body.Length, buf, 9);
         mHandshakeHash.BlockUpdate(buf, 0, buf.Length);
         mHandshakeHash.BlockUpdate(body, 0, body.Length);
     }
     return(message);
 }
示例#22
0
    public virtual byte[] CalculateMac(long seqNo, byte type, byte[] message, int offset, int length)
    {
        ProtocolVersion serverVersion = context.ServerVersion;
        bool            isSsl         = serverVersion.IsSsl;

        byte[] array = new byte[isSsl ? 11 : 13];
        TlsUtilities.WriteUint64(seqNo, array, 0);
        TlsUtilities.WriteUint8(type, array, 8);
        if (!isSsl)
        {
            TlsUtilities.WriteVersion(serverVersion, array, 9);
        }
        TlsUtilities.WriteUint16(length, array, array.Length - 2);
        mac.BlockUpdate(array, 0, array.Length);
        mac.BlockUpdate(message, offset, length);
        return(Truncate(MacUtilities.DoFinal(mac)));
    }
示例#23
0
        private void SendRecord(byte contentType, byte[] buf, int off, int len)
        {
            // Never send anything until a valid ClientHello has been received
            if (mWriteVersion == null)
            {
                return;
            }

            if (len > this.mPlaintextLimit)
            {
                throw new TlsFatalAlert(AlertDescription.internal_error);
            }

            /*
             * RFC 5246 6.2.1 Implementations MUST NOT send zero-length fragments of Handshake, Alert,
             * or ChangeCipherSpec content types.
             */
            if (len < 1 && contentType != ContentType.application_data)
            {
                throw new TlsFatalAlert(AlertDescription.internal_error);
            }

            int  recordEpoch          = mWriteEpoch.Epoch;
            long recordSequenceNumber = mWriteEpoch.AllocateSequenceNumber();

            BufferSegment ciphertext = mWriteEpoch.Cipher.EncodePlaintext(
                GetMacSequenceNumber(recordEpoch, recordSequenceNumber), contentType, buf, off, len);

            // TODO Check the ciphertext length?

            byte[] record = new byte[ciphertext.Count + RECORD_HEADER_LENGTH];
            TlsUtilities.WriteUint8(contentType, record, 0);
            ProtocolVersion version = mWriteVersion;

            TlsUtilities.WriteVersion(version, record, 1);
            TlsUtilities.WriteUint16(recordEpoch, record, 3);
            TlsUtilities.WriteUint48(recordSequenceNumber, record, 5);
            TlsUtilities.WriteUint16(ciphertext.Count, record, 11);
            Array.Copy(ciphertext.Data, ciphertext.Offset, record, RECORD_HEADER_LENGTH, ciphertext.Count);

            mTransport.Send(record, 0, record.Length);

            BufferPool.Release(ciphertext);
        }
    public static void WriteExplicitECParameters(byte[] ecPointFormats, ECDomainParameters ecParameters, Stream output)
    {
        ECCurve curve = ecParameters.Curve;

        if (ECAlgorithms.IsFpCurve(curve))
        {
            TlsUtilities.WriteUint8(1, output);
            WriteECParameter(curve.Field.Characteristic, output);
        }
        else
        {
            if (!ECAlgorithms.IsF2mCurve(curve))
            {
                throw new ArgumentException("'ecParameters' not a known curve type");
            }
            IPolynomialExtensionField polynomialExtensionField = (IPolynomialExtensionField)curve.Field;
            int[] exponentsPresent = polynomialExtensionField.MinimalPolynomial.GetExponentsPresent();
            TlsUtilities.WriteUint8(2, output);
            int i = exponentsPresent[exponentsPresent.Length - 1];
            TlsUtilities.CheckUint16(i);
            TlsUtilities.WriteUint16(i, output);
            if (exponentsPresent.Length == 3)
            {
                TlsUtilities.WriteUint8(1, output);
                WriteECExponent(exponentsPresent[1], output);
            }
            else
            {
                if (exponentsPresent.Length != 5)
                {
                    throw new ArgumentException("Only trinomial and pentomial curves are supported");
                }
                TlsUtilities.WriteUint8(2, output);
                WriteECExponent(exponentsPresent[1], output);
                WriteECExponent(exponentsPresent[2], output);
                WriteECExponent(exponentsPresent[3], output);
            }
        }
        WriteECFieldElement(curve.A, output);
        WriteECFieldElement(curve.B, output);
        TlsUtilities.WriteOpaque8(SerializeECPoint(ecPointFormats, ecParameters.G), output);
        WriteECParameter(ecParameters.N, output);
        WriteECParameter(ecParameters.H, output);
    }
示例#25
0
        /**
         * Encode this {@link CertificateRequest} to a {@link Stream}.
         *
         * @param output the {@link Stream} to encode to.
         * @throws IOException
         */
        public virtual void Encode(Stream output)
        {
            if (mCertificateTypes == null || mCertificateTypes.Length == 0)
            {
                TlsUtilities.WriteUint8(0, output);
            }
            else
            {
                TlsUtilities.WriteUint8ArrayWithUint8Length(mCertificateTypes, output);
            }

            if (mSupportedSignatureAlgorithms != null)
            {
                // TODO Check whether SignatureAlgorithm.anonymous is allowed here
                TlsUtilities.EncodeSupportedSignatureAlgorithms(mSupportedSignatureAlgorithms, false, output);
            }

            if (mCertificateAuthorities == null || mCertificateAuthorities.Count < 1)
            {
                TlsUtilities.WriteUint16(0, output);
            }
            else
            {
                IList derEncodings = Platform.CreateArrayList(mCertificateAuthorities.Count);

                int totalLength = 0;
                foreach (Asn1Encodable certificateAuthority in mCertificateAuthorities)
                {
                    byte[] derEncoding = certificateAuthority.GetEncoded(Asn1Encodable.Der);
                    derEncodings.Add(derEncoding);
                    totalLength += derEncoding.Length + 2;
                }

                TlsUtilities.CheckUint16(totalLength);
                TlsUtilities.WriteUint16(totalLength, output);

                foreach (byte[] derEncoding in derEncodings)
                {
                    TlsUtilities.WriteOpaque16(derEncoding, output);
                }
            }
        }
示例#26
0
        /**
         * Encode this {@link ServerNameList} to a {@link Stream}.
         *
         * @param output
         *            the {@link Stream} to encode to.
         * @throws IOException
         */
        public virtual void Encode(Stream output)
        {
            MemoryStream buf = new MemoryStream();

            byte[] nameTypesSeen = TlsUtilities.EmptyBytes;
            foreach (ServerName entry in ServerNames)
            {
                nameTypesSeen = CheckNameType(nameTypesSeen, entry.NameType);
                if (nameTypesSeen == null)
                {
                    throw new TlsFatalAlert(AlertDescription.internal_error);
                }

                entry.Encode(buf);
            }

            TlsUtilities.CheckUint16(buf.Length);
            TlsUtilities.WriteUint16((int)buf.Length, output);
            Streams.WriteBufTo(buf, output);
        }
        public byte[] ExportKeyingMaterial(string asciiLabel, byte[] context_value, int length)
        {
            if (context_value != null && !TlsUtilities.IsValidUint16(context_value.Length))
            {
                throw new ArgumentException("'context_value' must have length less than 2^16 (or be null)");
            }

            SecurityParameters sp = this.securityParameters;

            byte[] cr = sp.ClientRandom, sr = sp.ServerRandom;

            int seedLength = cr.Length + sr.Length;

            if (context_value != null)
            {
                seedLength += (2 + context_value.Length);
            }

            byte[] seed    = new byte[seedLength];
            int    seedPos = 0;

            Array.Copy(cr, 0, seed, seedPos, cr.Length);
            seedPos += cr.Length;
            Array.Copy(sr, 0, seed, seedPos, sr.Length);
            seedPos += sr.Length;
            if (context_value != null)
            {
                TlsUtilities.WriteUint16(context_value.Length, seed, seedPos);
                seedPos += 2;
                Array.Copy(context_value, 0, seed, seedPos, context_value.Length);
                seedPos += context_value.Length;
            }

            if (seedPos != seedLength)
            {
                throw new InvalidOperationException("error in calculation of seed for export");
            }

            return(TlsUtilities.PRF(this, sp.MasterSecret, asciiLabel, seed, length));
        }
示例#28
0
 internal virtual void WriteRecord(byte type, byte[] plaintext, int plaintextOffset, int plaintextLength)
 {
     if (mWriteVersion != null)
     {
         CheckType(type, 80);
         CheckLength(plaintextLength, mPlaintextLimit, 80);
         if (plaintextLength < 1 && type != 23)
         {
             throw new TlsFatalAlert(80);
         }
         if (type == 22)
         {
             UpdateHandshakeData(plaintext, plaintextOffset, plaintextLength);
         }
         Stream stream = mWriteCompression.Compress(mBuffer);
         byte[] array;
         if (stream == mBuffer)
         {
             array = mWriteCipher.EncodePlaintext(mWriteSeqNo++, type, plaintext, plaintextOffset, plaintextLength);
         }
         else
         {
             stream.Write(plaintext, plaintextOffset, plaintextLength);
             stream.Flush();
             byte[] bufferContents = GetBufferContents();
             CheckLength(bufferContents.Length, plaintextLength + 1024, 80);
             array = mWriteCipher.EncodePlaintext(mWriteSeqNo++, type, bufferContents, 0, bufferContents.Length);
         }
         CheckLength(array.Length, mCiphertextLimit, 80);
         byte[] array2 = new byte[array.Length + 5];
         TlsUtilities.WriteUint8(type, array2, 0);
         TlsUtilities.WriteVersion(mWriteVersion, array2, 1);
         TlsUtilities.WriteUint16(array.Length, array2, 3);
         Array.Copy(array, 0, array2, 5, array.Length);
         mOutput.Write(array2, 0, array2.Length);
         mOutput.Flush();
     }
 }
示例#29
0
        /**
         * Calculate the MAC for some given data.
         *
         * @param type    The message type of the message.
         * @param message A byte-buffer containing the message.
         * @param offset  The number of bytes to skip, before the message starts.
         * @param length  The length of the message.
         * @return A new byte-buffer containing the MAC value.
         */
        public /*virtual */ BufferSegment CalculateMac(long seqNo, byte type, byte[] message, int offset, int length)
        {
            ProtocolVersion serverVersion = context.ServerVersion;
            bool            isSsl         = serverVersion.IsSsl;

            int macHeaderLength = isSsl ? 11 : 13;

            byte[] macHeader = BufferPool.Get(macHeaderLength, true);
            TlsUtilities.WriteUint64(seqNo, macHeader, 0);
            TlsUtilities.WriteUint8(type, macHeader, 8);
            if (!isSsl)
            {
                TlsUtilities.WriteVersion(serverVersion, macHeader, 9);
            }
            TlsUtilities.WriteUint16(length, macHeader, macHeaderLength - 2);

            mac.BlockUpdate(macHeader, 0, macHeaderLength);
            mac.BlockUpdate(message, offset, length);

            BufferPool.Release(macHeader);

            return(Truncate(MacUtilities.DoFinalOptimized(mac)));
        }
示例#30
0
        public static byte[] CreateALPNExtension(System.Collections.Generic.List <string> protocols)
        {
            if (protocols == null)
            {
                throw new TlsFatalAlert(AlertDescription.internal_error);
            }

            // https://tools.ietf.org/html/rfc7301
            using (var buf = new BestHTTP.Extensions.BufferPoolMemoryStream())
            {
                using (var protoBuf = new BestHTTP.Extensions.BufferPoolMemoryStream())
                {
                    foreach (string protocol in protocols)
                    {
                        // Empty strings MUST NOT be included and byte strings MUST NOT be truncated.
                        if (string.IsNullOrEmpty(protocol))
                        {
                            continue;
                        }

                        byte[] asciiEncoding = Strings.ToAsciiByteArray(protocol);
                        if (asciiEncoding.Length < 1)
                        {
                            throw new TlsFatalAlert(AlertDescription.internal_error);
                        }
                        TlsUtilities.WriteOpaque8(asciiEncoding, protoBuf);
                        BestHTTP.PlatformSupport.Memory.BufferPool.Release(asciiEncoding);
                    }

                    TlsUtilities.CheckUint16(protoBuf.Length);
                    TlsUtilities.WriteUint16((int)protoBuf.Length, buf);
                    protoBuf.WriteTo(buf);
                }

                return(buf.ToArray());
            }
        }