// Copyright 2018 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.

package tls

import (
	
	
	
	
	
	

	
	
	
)

// This file contains the functions necessary to compute the TLS 1.3 key
// schedule. See RFC 8446, Section 7.

const (
	resumptionBinderLabel         = "res binder"
	clientHandshakeTrafficLabel   = "c hs traffic"
	serverHandshakeTrafficLabel   = "s hs traffic"
	clientApplicationTrafficLabel = "c ap traffic"
	serverApplicationTrafficLabel = "s ap traffic"
	exporterLabel                 = "exp master"
	resumptionLabel               = "res master"
	trafficUpdateLabel            = "traffic upd"
)

// expandLabel implements HKDF-Expand-Label from RFC 8446, Section 7.1.
func ( *cipherSuiteTLS13) ( []byte,  string,  []byte,  int) []byte {
	var  cryptobyte.Builder
	.AddUint16(uint16())
	.AddUint8LengthPrefixed(func( *cryptobyte.Builder) {
		.AddBytes([]byte("tls13 "))
		.AddBytes([]byte())
	})
	.AddUint8LengthPrefixed(func( *cryptobyte.Builder) {
		.AddBytes()
	})
	 := make([]byte, )
	,  := hkdf.Expand(.hash.New, , .BytesOrPanic()).Read()
	if  != nil ||  !=  {
		panic("tls: HKDF-Expand-Label invocation failed unexpectedly")
	}
	return 
}

// deriveSecret implements Derive-Secret from RFC 8446, Section 7.1.
func ( *cipherSuiteTLS13) ( []byte,  string,  hash.Hash) []byte {
	if  == nil {
		 = .hash.New()
	}
	return .expandLabel(, , .Sum(nil), .hash.Size())
}

// extract implements HKDF-Extract with the cipher suite hash.
func ( *cipherSuiteTLS13) (,  []byte) []byte {
	if  == nil {
		 = make([]byte, .hash.Size())
	}
	return hkdf.Extract(.hash.New, , )
}

// nextTrafficSecret generates the next traffic secret, given the current one,
// according to RFC 8446, Section 7.2.
func ( *cipherSuiteTLS13) ( []byte) []byte {
	return .expandLabel(, trafficUpdateLabel, nil, .hash.Size())
}

// trafficKey generates traffic keys according to RFC 8446, Section 7.3.
func ( *cipherSuiteTLS13) ( []byte) (,  []byte) {
	 = .expandLabel(, "key", nil, .keyLen)
	 = .expandLabel(, "iv", nil, aeadNonceLength)
	return
}

// finishedHash generates the Finished verify_data or PskBinderEntry according
// to RFC 8446, Section 4.4.4. See sections 4.4 and 4.2.11.2 for the baseKey
// selection.
func ( *cipherSuiteTLS13) ( []byte,  hash.Hash) []byte {
	 := .expandLabel(, "finished", nil, .hash.Size())
	 := hmac.New(.hash.New, )
	.Write(.Sum(nil))
	return .Sum(nil)
}

// exportKeyingMaterial implements RFC5705 exporters for TLS 1.3 according to
// RFC 8446, Section 7.5.
func ( *cipherSuiteTLS13) ( []byte,  hash.Hash) func(string, []byte, int) ([]byte, error) {
	 := .deriveSecret(, exporterLabel, )
	return func( string,  []byte,  int) ([]byte, error) {
		 := .deriveSecret(, , nil)
		 := .hash.New()
		.Write()
		return .expandLabel(, "exporter", .Sum(nil), ), nil
	}
}

// ecdheParameters implements Diffie-Hellman with either NIST curves or X25519,
// according to RFC 8446, Section 4.2.8.2.
type ecdheParameters interface {
	CurveID() CurveID
	PublicKey() []byte
	SharedKey(peerPublicKey []byte) []byte
}

func generateECDHEParameters( io.Reader,  CurveID) (ecdheParameters, error) {
	if  == X25519 {
		 := make([]byte, curve25519.ScalarSize)
		if ,  := io.ReadFull(, );  != nil {
			return nil, 
		}
		,  := curve25519.X25519(, curve25519.Basepoint)
		if  != nil {
			return nil, 
		}
		return &x25519Parameters{privateKey: , publicKey: }, nil
	}

	,  := curveForCurveID()
	if ! {
		return nil, errors.New("tls: internal error: unsupported curve")
	}

	 := &nistParameters{curveID: }
	var  error
	.privateKey, .x, .y,  = elliptic.GenerateKey(, )
	if  != nil {
		return nil, 
	}
	return , nil
}

func curveForCurveID( CurveID) (elliptic.Curve, bool) {
	switch  {
	case CurveP256:
		return elliptic.P256(), true
	case CurveP384:
		return elliptic.P384(), true
	case CurveP521:
		return elliptic.P521(), true
	default:
		return nil, false
	}
}

type nistParameters struct {
	privateKey []byte
	x, y       *big.Int // public key
	curveID    CurveID
}

func ( *nistParameters) () CurveID {
	return .curveID
}

func ( *nistParameters) () []byte {
	,  := curveForCurveID(.curveID)
	return elliptic.Marshal(, .x, .y)
}

func ( *nistParameters) ( []byte) []byte {
	,  := curveForCurveID(.curveID)
	// Unmarshal also checks whether the given point is on the curve.
	,  := elliptic.Unmarshal(, )
	if  == nil {
		return nil
	}

	,  := .ScalarMult(, , .privateKey)
	 := make([]byte, (.Params().BitSize+7)/8)
	return .FillBytes()
}

type x25519Parameters struct {
	privateKey []byte
	publicKey  []byte
}

func ( *x25519Parameters) () CurveID {
	return X25519
}

func ( *x25519Parameters) () []byte {
	return .publicKey[:]
}

func ( *x25519Parameters) ( []byte) []byte {
	,  := curve25519.X25519(.privateKey, )
	if  != nil {
		return nil
	}
	return 
}